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

ycc2008 2007-09-10 07:16:01
SQL2005

select col from table

结果集:
1
2
3
4
5

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

最好是用SQL语句来实现。。。我不想用游标来实现。。。
100分奉上。谢谢。。
...全文
404 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
pt1314917 2007-09-11
  • 打赏
  • 举报
回复
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+name+',' from product
print @sql

以前不知道这种写法,这次学会了。。
强烈的顶一下!
dawugui 2007-09-10
  • 打赏
  • 举报
回复
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
*/
randy_df 2007-09-10
  • 打赏
  • 举报
回复
哈,既然是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, '')
  • 打赏
  • 举报
回复
这样的问题都是典型的问题:
1、使用函数;
2、使用字符串连接;
3、使用coalesce函数。
lllyyymmm 2007-09-10
  • 打赏
  • 举报
回复
declare @s varchar(8000)
select @s=@s+','+结果列 from table
print @s
Limpire 2007-09-10
  • 打赏
  • 举报
回复
/*
Limpire:测试
*/

declare @output varchar(8000)

--输出系统表sysobjects的colid
select @output = coalesce(@output+',', '') + cast(colid as varchar) from syscolumns where id = object_id('sysobjects') order by colid
print @output
/*
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
*/

--输出系统表sysobjects的列名
set @output=null
select @output = coalesce(@output+',', '') + name from syscolumns where id = object_id('sysobjects') order by colid
print @output
/*
name,id,xtype,uid,info,status,base_schema_ver,replinfo,parent_obj,crdate,ftcatid,schema_ver,stats_schema_ver,type,userstat,sysstat,indexdel,refdate,version,deltrig,instrig,updtrig,seltrig,category,cache
*/
Limpire 2007-09-10
  • 打赏
  • 举报
回复
--如果col是数值型要转换一下:
declare @output varchar(8000)
select @output = coalesce(@output+',', '') + cast(col as varchar) from table
print @output
Limpire 2007-09-10
  • 打赏
  • 举报
回复
declare @output varchar(8000)
select @output = coalesce(@output+',', '') + col from table
print @output

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧