我需要将以下动态数据透视的结果存储到临时表中。有任何暗示吗?
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;
答案 0 :(得分:0)
我认为唯一的方法是使用OPENROWSET并在那里执行动态SQL查询。您需要将动态SQL(包括变量)作为字符串传递。
查看Insert results of a stored procedure into a temporary table