[英]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)
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.