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

求一条SQL语句的写法
能不能把一个表某个字段的值连成一个字符串返回?
比如:
表Student:
Names         Age         Localcation
张三             20                 河南
王二             20                 河北
李四             21                 安徽
...               ..                 ...
   

得到字符串:
"张三,王二,李四 "


谢谢^^^^^^^

------解决方案--------------------
新建函数:
create function f_str()
returns varchar(100)
as
begin
declare @str varchar(100)
set @str= ' '
select @str=@str+ ', '+names from 表名--这句写下相应的表名和列名
return stuff(@str,1,1, ' ')
end

调用
select dbo.f_str()
------解决方案--------------------
create table Student(Names varchar(10), Age int, Localcation varchar(10))
insert Student select '张三 ', 20, '河南 '
union all select '王二 ', 20, '河北 '
union all select '李四 ', 21, '安徽 '
go

declare @Names varchar(1000)
set @Names= ' '
select @Names=@Names+ ', '+Names from Student
select Names=stuff(@Names, 1, 1, ' ')


Names
-----------------
张三,王二,李四

(1 row(s) affected)
------解决方案--------------------
可以去除重复名字

create table Student(Names varchar(10), Age int, Localcation varchar(10))
insert Student select '张三 ', 20, '河南 '
union all select '王二 ', 20, '河北 '
union all select '王二 ', 20, '河北22 '
union all select '李四 ', 21, '安徽 '
go

declare @Names varchar(1000)
set @Names= ' '
select @Names=@Names+ ', '+Names from Student group by names
select Names=stuff(@Names, 1, 1, ' ')
drop table Student


李四,王二,张三