将所有符合条件的结果拼接成一列并用逗号隔开的一个sql语句


create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
create function [dbo].[f_str](@id int) returns nvarchar(1000)
as
begin
declare @str nvarchar(1000)
set @str = ''
select @str = @str + ',' + cast(value as nvarchar(900)) from tb where id = @id
set @str = right(@str , len(@str) - 1)
return @str
end
go
--调用函数
select id , value = dbo.f_str(id) from tb group by id
posted @ 2010-10-06 18:27  毛小毛  阅读(957)  评论(0编辑  收藏  举报