我创建了一个临时表变量,然后我需要对其进行旋转:
Declare @TempTable TABLE(
Name varchar(150),
CloseDate Date,
Revenue Float)
.... <add data to it> .....
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(CloseDate)
FROM @TempTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Name, ' + @cols + ' from
(select
t.Name,
t.CloseDate,
t.Revenue
from @TempTable as t
) x
pivot
(SUM(Revenue)
for CloseDate in (' + @cols + ')
) p '
execute(@query)
但是,我收到此错误:
Must declare the scalar variable "@TempTable".
当我使用普通的 SELECT 测试 @TempTable 变量时,它工作正常:
SELECT * from @TempTable
如何在查询字符串中成功引用变量?