1. 程式人生 > >sql中怎樣把同一張表中相同欄位的內容合併為一條記錄(合併的記錄的後面不加逗號)?

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、用標量函式查詢

     (1)建立標量函式

create function r(@cid int )
returns varchar(100)
as
begin
 declare @s varchar(100)
 select @s=isnull(@s+',','')+rtrim(id) from stuUnion where

[email protected]
 return @s
end;

  (2)用標量函式查詢

select cid,dbo.r(cid) AS id from stuUnion group by cid

三2、用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