一.定义表变量

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

—-次之栽方法

SELECT   CityName ,
                REPLACE(RTRIM(REPLACE(REPLACE(( SELECT  UserName
                                                FROM   
@T1 m
                                                where    m.CityName =
A.CityName
                                                 FOR XML AUTO
                                              ), ‘<m UserName=”‘,
”), ‘”/>’,
                                      ‘ ‘)), ‘ ‘, ‘,’)
       FROM     @T1 A

—-老二种植办法
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函数的功效是错过丢字符串最前边的逗号分隔符。

效果图:

图片 1

相关文章

网站地图xml地图