一.定义表变量
复制代码 代码如下:
declare @t1 table
(
userid int ,
username nvarchar(50),
cityname nvarchar(50)
);
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函数的作用是去掉字符串最前面的逗号分隔符。
效果图: