日期:2014-05-16 浏览次数:20475 次
----------------------------------------------------
/*如何将一列中所有的值一行显示
数据源
a
b
c
d
e
结果
a,b,c,d,e
*/
create table tb(col varchar(20))
insert tb values ('a')
insert tb values ('b')
insert tb values ('c')
insert tb values ('d')
insert tb values ('e')
go
--方法一
declare @sql varchar(1000)
set @sql = ''
select @sql = @sql + t.col + ',' from (select col from tb) as t
set @sql='select result = ''' + left(@sql , len(@sql) - 1) + ''''
exec(@sql)
/*
result
----------
a,b,c,d,e,
*/
--方法二
declare @output varchar(8000)
select @output = coalesce(@output + ',' , '') + col from tb
print @output
/*
a,b,c,d,e
*/
---方法三
declare @s varchar(1000)
select @s=isnull(@s+',' , '')+col from tb
select @s
/*
a,b,c,d,e
*/
drop table tb
-------------
create table t(v varchar(20))
insert into t
select 'dwa' union all
select 'da' union all
select 'sdf' union all
select 'gfhsd'
go
select distinct STUFF((select ','+v from t for xml path('')),1,1,'') xx
from t
/*
xx
dwa,da,sdf,gfhsd
*/