参考: CREATE table tb(id int,col nvarchar(10)) insert into tb select 1,'一' union all select 1,'二' union all select 1,'三' union all select 1,'四' union all select 1,'五' go --select stuff(select ' '+col from tb for xml path(''),1,1,'') as t select stuff(( select ' '+col from tb for xml path('') ),1,1,'')as t /* t ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 一 二 三 四 五(1 行受影响)*/ go drop table tb
/*如何将一列中所有的值一行显示 数据源 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 */drop table tb
CREATE table tb(id int,col nvarchar(10))
insert into tb select 1,'一' union all
select 1,'二' union all
select 1,'三' union all
select 1,'四' union all
select 1,'五'
go
--select stuff(select ' '+col from tb for xml path(''),1,1,'') as t
select stuff((
select ' '+col from tb for xml path('')
),1,1,'')as t
/*
t
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
一 二 三 四 五(1 行受影响)*/
go
drop table tb
数据源
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
*/drop table tb