一.定義表變量
代碼如下:
insert into @T1 (UserID,UserName,CityName) values (1,'a','上海')
insert into @T1 (UserID,UserName,CityName) values (2,'b','北京')
insert into @T1 (UserID,UserName,CityName) values (3,'c','上海')
insert into @T1 (UserID,UserName,CityName) values (4,'d','北京')
insert into @T1 (UserID,UserName,CityName) values (5,'e','上海')
select * from @T1
-----最優的方式
SELECT CityName,STUFF((SELECT ',' + UserName FROM @T1 subTitle WHERE CityName=A.CityName FOR XML PATH('')),1, 1, '') AS A
FROM @T1 A
GROUP BY CityName
----第二種方式
SELECT B.CityName,LEFT(UserList,LEN(UserList)-1)
FROM (
SELECT CityName,(SELECT UserName+',' FROM @T1 WHERE CityName=A.CityName FOR XML PATH('')) AS UserList
FROM @T1 A
GROUP BY CityName
) B
stuff(select ',' + fieldname from tablename for xml path('')),1,1,'')
這一整句的作用是將多行fieldname字段的內容串聯起來,用逗號分隔。
for xml path是SQL Server 2005以後版本支持的一種生成XML的方式。
stuff函數的作用是去掉字符串最前面的逗號分隔符。