Thursday, 12 September 2013

unpivot with dynamic columns plus column names

unpivot with dynamic columns plus column names

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.

No comments:

Post a Comment