在线等~~~~~请教一个高难度SQL语句问题,各个大哥帮帮忙吧

lovefreex 2012-02-17 03:44:23
create table test
(
id int identity(1,1),
name varchar(10),
)
go
insert into test values('A')
insert into test values('B')
insert into test values('C')


我想通过一条SQL语句,查询TEST表,想得到如下字符串:“A,B,C” 。请问如何实现?
...全文
113 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
lovefreex 2012-02-17
  • 打赏
  • 举报
回复
用2 3 5 6 7楼的方法,我是实现了。 唯一的遗憾是要写函数,不同通过一条SQL语句实现。

谢谢大家了。
AcHerat 2012-02-17
  • 打赏
  • 举报
回复
那就用字符串,xml是05及以上版本可以用的,楼主看看2 3 5 6 7楼的。
lovefreex 2012-02-17
  • 打赏
  • 举报
回复
谢谢大家,我执行select stuff((select ','+name from test for xml path('')),1,1,'')的时候,报XML附近有错误,我的是SQL 20000
请问是那边不对啊

唐诗三百首 2012-02-17
  • 打赏
  • 举报
回复
方法2,

create table test
(
id int identity(1,1),
name varchar(10),
)

insert into test values('A')
insert into test values('B')
insert into test values('C')


declare @names varchar(100)=''
select @names=@names+','+name from test
select stuff(@names,1,1,'') name

name
--------------------
A,B,C

(1 row(s) affected)
老猫五号 2012-02-17
  • 打赏
  • 举报
回复
declare @V varchar(8000)
set @V = ''
select @V = @V + ',' + name from test where id in (1,2,3);
select @V
唐诗三百首 2012-02-17
  • 打赏
  • 举报
回复

create table test
(
id int identity(1,1),
name varchar(10),
)

insert into test values('A')
insert into test values('B')
insert into test values('C')


select stuff((select ','+name from test for xml path('')),1,1,'') name

name
--------------------
A,B,C

(1 row(s) affected)
AcHerat 2012-02-17
  • 打赏
  • 举报
回复

create table test
(
id int identity(1,1),
name varchar(10),
)
go
insert into test values('A')
insert into test values('B')
insert into test values('C')
go

declare @str varchar(1000)

select @str = isnull(@str+',','')+name from test
print @str

drop table test

/*****************

A,B,C
老猫五号 2012-02-17
  • 打赏
  • 举报
回复
declare @V varchar(8000)
set @V = ''
select @V = @V + ',' + name from test where id in (1,2,3);
set @V = substring(@V,len(@V) -1);
select @V
AcHerat 2012-02-17
  • 打赏
  • 举报
回复

select stuff((select ','+name from test for xml path('')),1,1,'')

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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