简体   繁体   English

如何使用表变量进行动态数据透视?

[英]How to dynamic pivot with a table variable?

I have a table variable named: @table2 that contains... 我有一个名为:@ table2的表变量,其中包含...

col1 -- col2
id   -- 101
name -- Banana
age  -- 20
id   -- 102
name -- Pudding
age  -- 21

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(@trial2.col1) 
            FROM @trial2 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT *, ' + @cols + ' from ( select * from @trial2 ) x pivot ( max(col2) for col1 in (' + @cols + ') ) p ORDER BY p.s' execute(@query)


I'm having this error: "Must declare the scalar variable "@trial2"", in line "select @cols = STUFF((SELECT distinct ',' + QUOTENAME(@trial2.col1) " 我遇到此错误:“必须声明标量变量“ @ trial2””,在“选择@cols = STUFF((选择不同的','+ QUOTENAME(@ trial2.col1)””行中)
BUT when I change "@trial2.col1" to "col1", another error prompts: "Must declare the table variable "@trial2"", can you help me what do I do? 但是,当我将“ @ trial2.col1”更改为“ col1”时,另一个错误提示:“必须声明表变量“ @ trial2””,您能帮我做什么?

The query is running fine most likely, UNTIL you execute the generated SQL. 该查询很可能运行良好,直到您执行生成的SQL。 The RESULT of this query: 该查询的结果:

DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
DECLARE @trial2 table( col1 varchar(100) NOT NULL , col2 varchar(100) NOT NULL )

INSERT INTO @trial2    ([col1], [col2])
VALUES     ('id', '101'),('name', 'Banana'),('age', '20'),('id', '102'),('name', 'Pudding'),('age', '21')

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(t.col1) 
            FROM @trial2 t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT *, ' + @cols + ' from 
            (
                select *
                from @trial2 t
           ) x
            pivot 
            (
                max(col2)
                for col1 in (' + @cols + ')
            ) p 
            ORDER BY p.s'

select(@query)

is: 是:

SELECT *, [age],[id],[name] from ( select * from @trial2 t ) x pivot ( max(col2) for col1 in ([age],[id],[name]) ) p ORDER BY p.s

The problem is, at the point of executing that string, @trial2 DOES NOT EXIST. 问题是,在执行该字符串时,@ trial2不存在。 I think you should persist that table variable into a temp table (#trial2) and then you can expect your dynamic SQL to find the needed table. 我认为您应该将该表变量持久保存到临时表(#trial2)中,然后可以期望动态SQL查找所需的表。

Additionally you should not attempt to use 'SELECT *, ' + @cols in the final query, indeed you should not rely on select * in any production code. 另外,您不应在最终查询中尝试使用'SELECT *,'+ @cols,实际上,您不应在任何生产代码中使用select *。

also see this sqlfiddle: http://sqlfiddle.com/#!6/68b32/592 另请参阅此sqlfiddle: http ://sqlfiddle.com/#!6/68b32/592

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM