初始化表

create table test 
(
id int,
val varchar(5)
)
insert test 
select 1,'a' union all
select 1,'b' union all
select 2,'a' union all
select 2,'b' union all
select 2,'c' union all

得到的结果

         id       val

         1       a,b

         2       a,b,c

方法一:sql server 2000只能用自定义的函数解决(group by id,val值相加(字符串相加))

--自定义函数
create function func_ConcatStr(@id int)
returns varchar(50)
as
begin
declare @str varchar(50)
select @str=isnull(@str+',','')+val from test where id=@id
return @str
end
--调用函数
select id,val=func_ConcatStr(id) from test group by id

方法二:sql server 2005中的方法(for xml path)

select id, [val]=stuff((select ',' + [val] from test as a where a.id = b.id for xml path('')),1 ,1,'')
from test as b
group by id

 

 posted on 2015-08-01 18:33  会飞的金鱼  阅读(1839)  评论(0)    收藏  举报