简体   繁体   中英

How to dynamic pivot with a table variable?

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)


I'm having this error: "Must declare the scalar variable "@trial2"", in line "select @cols = STUFF((SELECT distinct ',' + 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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