首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求一合并记录的存储过程,该怎么处理

2012-03-23 
求一合并记录的存储过程有一表的记录为:IDNameWORKTIME111test12111test21231test32231test43231test51...

求一合并记录的存储过程
有一表的记录为:  
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
------------------------------
111test1,test23
231test3,test4,test56

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

drop table Tab01
drop function Fun01

热点排行