日期:2014-05-17 浏览次数:20473 次
declare @v nvarchar(500)
select @v=''
select @v=@v+' '+a+' '+b+' '+c from tab
select @v
select a+' '+b+' '+c+' ' from tab for xml path('')
create table zy
(no int, a varchar(5), b varchar(5), c varchar(5))
insert into zy
select 1, 'a1', 'b1', 'c1' union all
select 2, 'a2', 'b2', 'c2' union all
select 3, 'a3', 'b3', 'c3'
select * from zy
/*
no a b c
----------- ----- ----- -----
1 a1 b1 c1
2 a2 b2 c2
3 a3 b3 c3
(3 row(s) affected)
*/
declare @tsql varchar(6000)
select @tsql='select '
select @tsql=@tsql+' max(da'+rtrim(no)+') da'+rtrim(no)+','
+' max(db'+rtrim(no)+') db'+rtrim(no)+','
+' max(dc'+rtrim(no)+') dc'+rtrim(no)+','
from (select distinct no from zy) z
select @tsql=left(@tsql,len(@tsql)-1)+' from (select no,'
select @tsql=@tsql+' max(case when no='+rtrim(no)+' then a else '''' end) da'+rtrim(no)+','
+' max(case when no='+rtrim(no)+' then b else '''' end) db'+rtrim(no)+','
+' max(case when no='+rtrim(no)+' then c else '''' end) dc'+rtrim(no)+','
from (select distinct no from zy) z
select @tsql=left(@tsql,len(@tsql)-1)+' from zy group by no) t'