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.