--生成测试数据
create table t(id int,psid int,name varchar(80))
insert into t select 1,1,'name1'
insert into t select 2,1,'name2'
insert into t select 3,2,'name1'
insert into t select 4,2,'name2'
insert into t select 5,3,'name1'
insert into t select 6,5,'name1'
insert into t select 7,6,'name1'
insert into t select 8,7,'name4'
go
--创建用户定义函数
ALTER function f_str(@psid int)
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+','+name from t where psid = @psid
set @ret = stuff(@ret,1,1,'')
return @ret
end
--执行查询
select distinct name=dbo.f_str(psid) from t
go
--输出结果
/*
name
-----------
name1
name1,name2
name4
*/
--删除测试数据
drop function f_str
drop table t