首页 > 技术文章 > 多少行转多少列

zmztya 2016-07-18 15:39 原文

SQL code
create table #t(col varchar(10))
insert into #t values('A')
insert into #t values('B')
insert into #t values('C')
insert into #t values('D')
insert into #t values('E')
declare @s varchar(8000)
select @s = isnull(@s + ',','')+'[col'+col+'] = max(case when col = '''+col+''' then col end)'
from #t
exec('select '+@s + ' from #t')
drop table #t
/*
colA       colB       colC       colD       colE
---------- ---------- ---------- ---------- ----------
A          B          C          D          E

  

推荐阅读