1

I have successfully constructed the output that I have been looking for from using dynamic SQL to create a pivot table with dynamically created column names.

My code is:

IF OBJECT_ID('tempdb..#TempDB') IS NOT NULL
DROP TABLE #TempDB
SELECT CASEID, FORMNAME, NAME, VALUE INTO #TempDB FROM dbo.EFORM WHERE FORMNAME='IncidentReporting'

 IF OBJECT_ID('tempdb..#TempDB1') IS NOT NULL
DROP TABLE #TempDB1
SELECT DISTINCT Name INTO #TempDB1 FROM #TempDB

DECLARE @columns varchar(max)
DECLARE @query varchar(max)

SELECT @columns = COALESCE(@columns + ',[' + cast([Name] as varchar(100)) + ']', 
             '[' + cast([Name] as varchar(100))+ ']') 
             FROM #TempDB1

SET @query = 'SELECT * FROM #TempDB AS PivotData '
SET @query = @query  + 
'PIVOT (MAX(VALUE) FOR [NAME] IN (' + @columns + ')) AS p'

EXEC (@query)

This successfully gives me results like:

CASEID  FORMNAME             Column1    Column2 Column3
501000000621    IncidentReporting   Value1  Valuea  Valuev
501000000622    IncidentReporting   Value2  Valueb  Valuew
601000000126    IncidentReporting   Value3  Valuec  Valuex
601000000127    IncidentReporting   Value4  Valued  Valuey
601000000128    IncidentReporting   Value5  Valuee  Valuez

These results, outputed from the @query variable, are in exactly the format that I want a table of these results to be in.

Can anyone tell me how to get the results that are in the @query variable into a standard SQL table?

I have tried doing a statement like this, but I get the message "Incorrect syntax near ' + @columns + '":

SELECT *
INTO #TempDB4
FROM (SELECT * FROM #TempDB AS PivotData 
PIVOT (MAX(VALUE) FOR [NAME] IN (' + @columns + ')) AS p)

Many thanks in advance.

1 Answer 1

2

In your existing code, add your into to this line:

SET @query = 'SELECT * FROM #TempDB AS PivotData '

so that you get:

SET @query = 'SELECT * INTO #TempDB4 FROM #TempDB AS PivotData '

Or add insert in the same manner.

To get your unsuccessful query to work as you expect, you'd have to turn that into dynamic SQL, much like your successful query, and call it using exec or sp_executesql

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for this. You have no idea how much Googling failed to come up with this simple solution. Works perfectly!
In order for this to work, you need to make it a global temp variable. ##temp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.