合并多条记录的同一字段值SQL语句

1.生成测试数据:
create table team(name varchar(32),person varchar(32));

insert into team values('A','Tom');
insert into team values('A','Jim');
insert into team values('A','Anny');
insert into team values('B','Ivy');
insert into team values('B','Henry');   
insert into team values('C','Dar');
insert into team values('C','Rk');
insert into team values('D','Cenic');

select * from team;
合并多条记录的同一字段值SQL语句_第1张图片

2.创建合并团队成员姓名自定义函数:
create   function   fun_combName(@teamname varchar(32))  
  returns   varchar(4000)  
  as  
  begin  
          declare @temp varchar(4000)  
          set @temp = ''  
          select @temp = @temp+';'+person from team where name = @teamname  
          set @temp = stuff(@temp,1,1,'')  
          return   @temp    
  end

3.执行查询语句:
select name,person = dbo.fun_combName(name) from team group by name order by name;


注:测试完可以删除测试数据:
drop function fun_combName;
drop table team;

你可能感兴趣的:(sql,数据库,记录,字段,语句)