日期:2014-05-18  浏览次数:20585 次

如何把结果集变成一个字符串输出?
SQL2005

select   col   from   table

结果集:
1
2
3
4
5

我想要的是用逗号隔开的一个字符串
1,2,3,4,5

最好是用SQL语句来实现。。。我不想用游标来实现。。。
100分奉上。谢谢。。

------解决方案--------------------
declare @output varchar(8000)
select @output = coalesce(@output+ ', ', ' ') + col from table
print @output

------解决方案--------------------
declare @s varchar(8000)
select @s=@s+ ', '+结果列 from table
print @s
------解决方案--------------------
这样的问题都是典型的问题:
1、使用函数;
2、使用字符串连接;
3、使用coalesce函数。
------解决方案--------------------
哈,既然是SQL2005,就来个新方法吧.简单又好玩:

-- 先生成一张临时表玩下 :)
if exists (select * from dbo.sysobjects where id = object_id(N 'temtable ') and OBJECTPROPERTY(id, N 'IsUserTable ') = 1) drop table temtable
SELECT * INTO temtable
FROM(
SELECT '1 ' AS temcol
UNION ALL
SELECT '2 ' AS temcol
UNION ALL
SELECT '3 ' AS temcol
)T

--SQL 主体
SELECT temcol = STUFF(REPLACE(REPLACE(
(
SELECT temcol
FROM temtable AS N
FOR XML AUTO
), ' <N temcol= " ', ', '), ' "/> ', ' '), 1, 1, ' ')
------解决方案--------------------
create table tb(id varchar(10))
insert into tb values( '1 ')
insert into tb values( '2 ')
insert into tb values( '3 ')
insert into tb values( '4 ')
insert into tb values( '5 ')

declare @id varchar(8000)
set @id = ' '
select @id = @id + id + ', ' from tb
set @id = left(@id,len(@id) - 1)
print @id

drop table tb

/*
1,2,3,4,5
*/

------解决方案--------------------
declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+name+ ', ' from product
print @sql

以前不知道这种写法,这次学会了。。
强烈的顶一下!