Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to unpivot a table with a large number of columns in the format of:

PID UID col1 col2 col3...

The dynamic SQL below will get me almost everything except the name of the column. The goal is to fill in the "ID" field with the name of the column from which the unpivot value originated.

-- Build list of cols we want to unpivot (skip PID & UID)
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'MyTable' and c.name not in ('PID', 'UID') order by c.colid

declare @query nvarchar(max)  

select @query = N'
select PID, [UID], ID, Val
from 
    (
    select PID, UID, ''ID'' as ID, ' + @cols + '
    from MyTable
    where UID <> 0
    ) as cp
    unpivot
    (
    Val for Vals in (' + @cols + ')
    ) as up
'
exec sp_executesql @query 

I thought maybe I could do some sort of join with syscolumns & MyTable and then do a second unpivot but I haven't been able to figure it out.

Ultimately my query should return

PID UID ID          Val

123 456 'col1 name' 'xyz'
123 456 'col2 name' 'def'
123 333 'col1 name' 'fdf'
...

So while I know how to get the name of the columns in order to generate the dynamic SQL for the unpivot, I don't know how to join the name of the columns into the output of the unpivot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
501 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can reference the column name from the val for col in part of the unpivot. Col gets the column name

Example Fiddle

-- Build list of cols we want to unpivot (skip PID & UID)
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'MyTable' and c.name not in ('PID', 'UID') order by c.colid

declare @query nvarchar(max)  

select @query = N'
select PID, [UID], Col as ID, Val
from 
    (
    select PID, UID, ' + @cols + '
    from MyTable
    where UID <> 0
    ) as cp
    unpivot
    (
    Val for Col in (' + @cols + ')
    ) as up
'
exec sp_executesql @query 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...