将动态数据透视的结果存储到临时表
Posted
技术标签:
【中文标题】将动态数据透视的结果存储到临时表【英文标题】:store the result of the a dynamic pivot to a temp table 【发布时间】:2016-06-28 03:45:57 【问题描述】:我需要将以下动态数据透视的结果存储到临时表中。有什么建议吗?
DECLARE @serviceid int = 66;
DECLARE @SQL nvarchar(max);
WITH E(n) AS( SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n) ),
cteTally(n) AS( SELECT TOP(SELECT /*TOP 1*/ COUNT(*) cnt
FROM #T WHERE serviceid = @serviceid--Comment this and uncomment the other part to use the full table. /*GROUP BY serviceid
ORDER BY cnt DESC*/) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
FROM E a, E b )
SELECT @SQL = N'WITH CTE AS(' + CHAR(10) + CHAR(9) + N'SELECT *,
ROW_NUMBER() OVER( PARTITION BY serviceid ORDER BY serviceid) AS row_num' + CHAR(10) + CHAR(9) + N'FROM #T'
+ CHAR(10) + CHAR(9) + N'WHERE serviceid = @serviceid' + CHAR(10) + N')' + CHAR(10) + CHAR(9)
+ N'SELECT serviceid' + CHAR(10) + CHAR(9) + N',ProgramId' + CHAR(10)
+ (SELECT CHAR(9) + ',MAX( CASE WHEN row_num = ' + CAST( n AS nvarchar(3))
+ ' THEN Firstbilleddate END) AS Firstbilleddate' + CAST( n AS nvarchar(3))
+ CHAR(10) FROM cteTally FOR XML PATH(''), TYPE).value('./text()[1]', 'nvarchar(max)')
+ (SELECT CHAR(9) + ',MAX( CASE WHEN row_num = ' + CAST( n AS nvarchar(3)) + ' THEN CoveragePlanName END) AS CoveragePlanName'
+ CAST( n AS nvarchar(3)) + CHAR(10) FROM cteTally
FOR XML PATH(''), TYPE).value('./text()[1]', 'nvarchar(max)')
+ CHAR(9) + N',SUM( ChargeAmount) AS ChargeAmount' + CHAR(10) + CHAR(9) + N',SUM( AdjustmentAmount) AS AdjustmentAmount'
+ CHAR(10) + CHAR(9) + N',SUM( PaymentAmount) AS PaymentAmount' + CHAR(10) + N'FROM CTE' + CHAR(10) + N'GROUP BY serviceid'
+ CHAR(10) + CHAR(9) + N',ProgramId;' + CHAR(10); PRINT @SQL; EXECUTE sp_executesql @SQL, N'@serviceid int', @serviceid;
【问题讨论】:
【参考方案1】:我认为唯一的方法是使用 OPENROWSET 并在那里执行您的动态 sql 查询。您需要将动态 SQL(包括变量)作为字符串传递。
看看Insert results of a stored procedure into a temporary table
【讨论】:
以上是关于将动态数据透视的结果存储到临时表的主要内容,如果未能解决你的问题,请参考以下文章