0

我有一张桌子

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".
4

1 回答 1

1

动态 SQL 在不同的上下文中执行,因此它不会有表变量。请改用临时表 (#T)。

于 2015-10-31T05:53:34.350 回答