unpivot with dynamic columns plus column names

后端 未结 1 1521
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 15:09

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

相关标签:
1条回答
  • 2020-11-30 15:16

    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 
    
    0 讨论(0)
提交回复
热议问题