无法正确执行 Dynamic Pivot?
Could not execute properly the Dynamic Pivot?
我有一个table
DECLARE @T TABLE(Val1 VARCHAR(20), Id INT, Val2 INT)
INSERT INTO @T VALUES
('X',1,2),
('Y',2,3)
如果我想 运行 一个 PIVOT (STATIC),查询是
SELECT ID, [X],[Y] from @T
PIVOT
(
MAX(Val2)
FOR Val1 IN ([X],[Y])
) AS X
ORDER BY 1
它按预期工作。我们如何在 Dynamic PIVOT 中执行相同的操作?
我的尝试
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Val1)
from @T
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ID, ' + @cols + N' from @T
PIVOT
(
MAX(Val2)
FOR Val1 IN (' + @cols + N')
) AS X
ORDER BY 1'
exec sp_executesql @query
错误:
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@T".
动态 SQL 在不同的上下文中执行,因此它不会有 table 变量。请改用临时 table (#T)。
我有一个table
DECLARE @T TABLE(Val1 VARCHAR(20), Id INT, Val2 INT)
INSERT INTO @T VALUES
('X',1,2),
('Y',2,3)
如果我想 运行 一个 PIVOT (STATIC),查询是
SELECT ID, [X],[Y] from @T
PIVOT
(
MAX(Val2)
FOR Val1 IN ([X],[Y])
) AS X
ORDER BY 1
它按预期工作。我们如何在 Dynamic PIVOT 中执行相同的操作?
我的尝试
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Val1)
from @T
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ID, ' + @cols + N' from @T
PIVOT
(
MAX(Val2)
FOR Val1 IN (' + @cols + N')
) AS X
ORDER BY 1'
exec sp_executesql @query
错误:
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@T".
动态 SQL 在不同的上下文中执行,因此它不会有 table 变量。请改用临时 table (#T)。