Reputation: 61
I have a table variable named: @table2 that contains...
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)
Upvotes: 3
Views: 2203
Reputation: 35583
The query is running fine most likely, UNTIL you execute the generated 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. 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.
Additionally you should not attempt to use 'SELECT *, ' + @cols in the final query, indeed you should not rely on select * in any production code.
also see this sqlfiddle: http://sqlfiddle.com/#!6/68b32/592
Upvotes: 0