首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求一条SQL语句的写法解决方案

2012-02-01 
求一条SQL语句的写法能不能把一个表某个字段的值连成一个字符串返回?比如:表Student:NamesAgeLocalcation

求一条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


李四,王二,张三

热点排行
Bad Request.