1

我正在尝试使用以下格式对包含大量列的表进行反透视:

PID UID col1 col2 col3...

下面的动态 SQL 将得到我几乎所有的东西,除了列的名称。目标是在“ID”字段中填写 unpivot 值源自的列的名称。

-- 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 

我想也许我可以使用 syscolumns 和 MyTable 进行某种联接,然后进行第二次反透视,但我无法弄清楚。

最终我的查询应该返回

PID UID ID          Val

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

因此,虽然我知道如何获取列的名称以便为 unpivot 生成动态 SQL,但我不知道如何将列的名称连接到 unpivot 的输出中。

4

1 回答 1

3

val for col in您可以从unpivot 部分引用列名。col 获取列名

示例小提琴

-- 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 
于 2013-09-12T22:51:45.200 回答