我已经成功地构建了我一直在使用动态 SQL 来创建具有动态创建的列名的数据透视表的输出。
我的代码是:
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)
这成功地给了我这样的结果:
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
从@query 变量输出的这些结果正是我希望这些结果的表格所在的格式。
谁能告诉我如何将@query 变量中的结果放入标准 SQL 表中?
我试过做这样的声明,但我收到消息“'+ @columns +'附近的语法不正确”:
SELECT *
INTO #TempDB4
FROM (SELECT * FROM #TempDB AS PivotData
PIVOT (MAX(VALUE) FOR [NAME] IN (' + @columns + ')) AS p)
提前谢谢了。