sql server 使用for xml path 将1列多行转换为字符串连接起来
create table tb ([id] int,[name] varchar(2))insert into tbselect 1,'aa' union allselect 2,'bb' union allselect 1,'cc' union allselect 3,'dd' union allselect 2,'ee' select * from tb--查询select id, name=stuff((select ','+name from tb where id=t.id for xml path('')),1,1,'')from tb tgroup by id 方法二: CREATE FUNCTION GET_STRING(@ID INT)RETURNS VARCHAR(50)AS BEGIN DECLARE @NAME VARCHAR(500) SELECT @NAME=ISNULL(@NAME+',','')+NAME FROM TB WHERE ID=@ID RETURN @NAME ENDSELECT ID ,DBO.GET_STRING(ID)NAME FROM TB GROUP BY ID-----------------------------------在oracle中,是有相对应的函数,sys_connect_by_path函数。先在这里把oracle的函数实现也写下吧select id ,itrim(max(sys_connect_by_path(name,','))) as namefrom (select id ,name ,lead(rnFirst) over(partition by no order by rnFirst)rnNext from (select a.id ,a.name ,row_number() over(order by a.id,a.name desc) rnFirst from @t a) tmpTable1) tmpTable2start with rnNext is nullconnect by rnNext = PRior rnFirstgroup by id以上是实现oracle中的行转列方式。********************************************下面我们来看一下sqlserver的,因为sqlserver没提供类似的函数,不知道sqlserver2012提供没不过sqlserver支持起来也很简单,使用cross apply和for xml path组合来用,这两个单独都知道是怎么回事,怎么使用,但是真不知道还有它俩组合来完成这个功能的,感到很是不可思议,这里要感谢下网络上的人,原来自己写东西都是把所学到的知识记录到本机,从不放到网上,也可能是最近吧,好多工作不会,都是通过网络帮助,就把我所知道的东西也都放到网上来,大家一起学习。sqlserver:select id, SUBSTRING(names, 1, len(names)-1) from @t AS A cross APPLY(SELECT NAME + ',' FROM @t AS B WHERE A.id = B.id FOR XML PATH('')) D (names)GROUP BY id, names