合併相同記錄字段數據

--生成測試數據
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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章