select convert(nvarchar(50),Id)+',' from tab for xml path('')
--> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([name] int) insert [tb] select 1 union all select 2 union all select 3 union all select 4 union all select 5 --------------开始查询------------------------- SELECT STUFF((SELECT ','+LTRIM([name]) FROM [tb] FOR XML PATH('')),1,1,'') AS [name] ----------------结果---------------------------- /* name -------------- 1,2,3,4,5 */
---------------------------------------------------- /*如何将一列中所有的值一行显示 数据源 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 -------------
select convert(nvarchar(50),Id)+',' from tab for xml path('')
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] int)
insert [tb]
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5
--------------开始查询-------------------------
SELECT STUFF((SELECT ','+LTRIM([name]) FROM [tb] FOR XML PATH('')),1,1,'') AS [name]
----------------结果----------------------------
/*
name
--------------
1,2,3,4,5
*/
/*如何将一列中所有的值一行显示
数据源
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
-------------