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

求一合并记录的存储过程
有一表的记录为:  
ID       Name     WORKTIME  
111     test1         2  
111     test2         1
231     test3         2
231     test4         3
231     test5         1
....

我想用一存储过程实现ID相同记录合并为一条记录,即:
ID                       Name                       WORKLOAD
111                     test1,test2         3
231                     test3,test4,test5     6      

请高手赐教,谢谢。

------解决方案--------------------
--创建测试数据
create table Tab01 (ID varchar(3), Name varchar(100), WORKTIME int)
insert Tab01
select '111 ', 'test1 ', '2 ' union all
select '111 ', 'test2 ', '1 ' union all
select '231 ', 'test3 ', '2 ' union all
select '231 ', 'test4 ', '3 ' union all
select '231 ', 'test5 ', '1 '

--SQL Server 2000中,一般都是用自定义函数去处理:
create function Fun01(@ID varchar(3))
returns varchar(1000)
as
begin
declare @Com varchar(1000)
set @Com = ' '
select @Com = @Com + ', ' + Name from Tab01 where ID = @ID
return(stuff(@Com, 1, 1, ' '))
end
go


--调用函数Fun01得到结果
select ID, dbo.Fun01(ID), sum(WORKTIME) from Tab01 group by ID
/*结果
ID
---- --------------- -----------
111 test1,test2 3
231 test3,test4,test5 6

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

drop table Tab01
drop function Fun01