在不知道列的情况下,您无法在一个查询中进行透视或取消透视。
假设您有权限,您可以做的是查询sys.columns
以获取源表的字段名称,然后动态构建一个 unpivot 查询。
--Source table
create table MyTable (
id int,
Field1 nvarchar(10),
Field2 nvarchar(10),
Field3 nvarchar(10)
);
insert into MyTable (id, Field1, Field2, Field3) values ( 1, 'aaa', 'bbb', 'ccc' );
insert into MyTable (id, Field1, Field2, Field3) values ( 2, 'eee', 'fff', 'ggg' );
insert into MyTable (id, Field1, Field2, Field3) values ( 3, 'hhh', 'iii', 'jjj' );
--key/value table
create table MyValuesTable (
id int,
[field] sysname,
[value] nvarchar(10)
);
declare @columnString nvarchar(max)
--This recursive CTE examines the source table's columns excluding
--the 'id' column explicitly and builds a string of column names
--like so: '[Field1], [Field2], [Field3]'.
;with columnNames as (
select column_id, name
from sys.columns
where object_id = object_id('MyTable','U')
and name <> 'id'
),
columnString (id, string) as (
select
2, cast('' as nvarchar(max))
union all
select
b.id + 1, b.string + case when b.string = '' then '' else ', ' end + '[' + a.name + ']'
from
columnNames a
join columnString b on b.id = a.column_id
)
select top 1 @columnString = string from columnString order by id desc
--Now I build a query around the column names which unpivots the source and inserts into the key/value table.
declare @sql nvarchar(max)
set @sql = '
insert MyValuestable
select id, field, value
from
(select * from MyTable) b
unpivot
(value for field in (' + @columnString + ')) as unpvt'
--Query's ready to run.
exec (@sql)
select * from MyValuesTable
如果您从存储过程中获取源数据,您可以使用OPENROWSET
将数据放入表中,然后检查该表的列名。此链接显示了如何执行该部分。
https://stackoverflow.com/a/1228165/300242
最后说明:如果您使用临时表,请记住您从以下tempdb.sys.columns
方式获取列名:
select column_id, name
from tempdb.sys.columns
where object_id = object_id('tempdb..#MyTable','U')