sql拼2个字段里的字符串

select * from tb

id value
1 aa
1 bb
2 aaa
2 bbb
2 ccc

select id, [value] = stuff((select ',' + [value] from tb t where id = tb.id for xml path('')) , 1 , 1 , '')
from tb        
group by id

id value
1 aa,bb
2 aaa,bbb,ccc

create function f_str(@id int) returns varchar(100)
as
begin
    declare @str varchar(1000)
    set @str = ''
    select @str = @str + ',' + cast(value as varchar) from tb where id = @id
    set @str = right(@str , len(@str) - 1)
    return @str
end

posted @ 2012-01-13 15:25  emmy  阅读(329)  评论(1编辑  收藏  举报