22,206
社区成员
发帖
与我相关
我的任务
分享
drop table if EXISTS tab;
CREATE TABLE tab(
a INT,
b INT,
c INT,
d int
);
INSERT INTO tab
SELECT 1,2,3,4;
select * from
(
select 'a' as title,a as cnt from tab
union all
select 'b' as title,b as cnt from tab
union all
select 'c' as title,c as cnt from tab
union all
select 'd' as title,d as cnt from tab
) t;
IF OBJECT_ID('tab') IS NOT NULL
DROP TABLE tab
CREATE TABLE tab(
a INT,
b INT,
c INT,
d int
)
INSERT INTO tab
SELECT 1,2,3,4
--测试数据结束
declare @sql nvarchar(4000)
select @sql=isnull(@sql+',','')+quotename(Name)
from syscolumns
where ID=object_id('tab')
order by Colid
PRINT @sql
set @sql='select [title],[cnt] from tab unpivot ([cnt] for [title] in('+@sql+'))b'
exec(@sql)