SQL-字符串合并

时间:2020-12-23 06:44:08

create table tb(id int, value varchar(10)) 
insert into tb values(1, 'aa') 
insert into tb values(1, 'bb') 
insert into tb values(2, 'aaa') 
insert into tb values(2, 'bbb') 
insert into tb values(2, 'ccc') 
go 
-- 方法一:
-- 1. 创建Function
create function dbo.f_str(@id varchar(10)) returns varchar(1000) 
as 
begin 
  declare @str varchar(1000) 
  select @str = isnull(@str + ',' , '') + cast(value as varchar) from tb where id = @id 
  return @str 
end 
go 
-- 2. 调用Function 
select id , value = dbo.f_str(id) from tb group by id

drop function dbo.f_str

-- 方法二:
select id, [value] = stuff((select ',' + [value]
                from tb t where id = tb.id
                for xml path('')) , 1 , 1 , '') 
from tb 
group by id 
drop table tb