怎样把一张表的某个字段(字符型)下的所有值拼起来

来源:百度知道 编辑:UC知道 时间:2024/06/25 21:08:51
例如:
name
张三
李四
...
怎样得到‘张三李四...’

Oracle下一字段显示多条数据:
select wm_concat(t.company_no) from st_bpfs_company t

MSSQL下:
--生成测试数据
create table 表(部门 int,人员 varchar(20))
insert into 表 select 1,'张三'
insert into 表 select 1,'李四'
insert into 表 select 1,'王五'
insert into 表 select 2,'赵六'
insert into 表 select 2,'邓七'
insert into 表 select 2,'刘八'
go

--创建用户定义函数
create function f_str(@department int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+','+人员 from 表 where 部门 = @department
set @ret = stuff(@ret,1,1,'')
return @ret
end
go
--执行
select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
go
--输出结果
/*
部门 人员
---- --------------
1 张三,李四,王五
2 赵六,邓七,刘八
*/

--删除测试数据
drop function f_str
drop table 表