SQL 同一張表中相同字段的內容合並為一條記錄(不同字段的那一列每個記錄后面加逗號)


一、創建表
create table stuUnion
(
 sid int identity primary key,
 cid int,
 id varchar(500)
)
 
二、添加數據
insert into stuUnion
select 1,'a' union
select 1,'b' union
select 2,'c' union
select 2,'d' union
select 3,'e' union
select 3,'f' union
select 3,'g'
 
三、用標量函數查詢
(1)創建標量函數
create function b(@cid int)
returns varchar(500)
as
begin
declare @s varchar(500)
select @s=isnull(@s+'','')+rtrim(id)+',' from stuUnion where cid=@cid
return @s
end;
 
(2)用標量函數查詢
select cid,dbo.b(cid) as id from stuUnion group by cid
 
三、用sqlserver的xml
select cid,ID=STUFF((select ' '+rtrim(id)+',' from stuUnion where st.cid=cid order by id for XML path('')),1,1,'') from stuUnion st group by cid

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM