简体   繁体   English

如何将动态枢轴变量输出另存为 SQL Server 表

[英]How To Save Dynamic Pivot Variable Output As SQL Server Table

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.我已经成功构建了我一直在寻找的输出,使用动态 SQL 创建一个带有动态创建的列名的数据透视表。

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.从@query 变量输出的这些结果正是我想要这些结果的表格的格式。

Can anyone tell me how to get the results that are in the @query variable into a standard SQL table?谁能告诉我如何将 @query 变量中的结果放入标准 SQL 表中?

I have tried doing a statement like this, but I get the message "Incorrect syntax near ' + @columns + '":我试过做这样的语句,但我收到消息“' + @columns + ' 附近的语法不正确”:

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

Many thanks in advance.提前谢谢了。

In your existing code, add your into to this line:在现有的代码,添加into该行:

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.或者以同样的方式添加insert

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为了让不成功的查询按预期工作,您必须将其转换为动态 SQL,就像您的成功查询一样,并使用execsp_executesql调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM