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

求个SQL存储过程..谢谢了
将一个表中A中ID重复的字段name全部合并的存储过程;

表A
  ID name ID name
1 A 1 ABC
1 B 合并后 2 H
2 H 3 CD
3 CD
1 C



------解决方案--------------------
SQL code
create table tb(ID int, name varchar(10))
insert into tb values(1, 'A')
insert into tb values(1, 'B')
insert into tb values(2, 'H')
insert into tb values(3, 'CD') 
insert into tb values(1, 'C') 
go

--创建一个合并的函数
create function f_hb(@id int)
returns varchar(8000)
as
begin
  declare @str varchar(8000)
  set @str = ''
  select @str = @str + cast(name as varchar) from tb where id = @id
  set @str = right(@str , len(@str))
  return(@str)
End
go

--调用自定义函数得到结果:
select distinct id ,dbo.f_hb(id) as name from tb

drop table tb
drop function dbo.f_hb

/*
id          name    
----------- --------
1           ABC
2           H
3           CD

(所影响的行数为 3 行)
*/