sql中合并列方法

方法一:创建合并列函数

 

-------创建一个方法----------

CREATE FUNCTION dbo.Role_Name(@AdminID int)
return varchar(8000)
AS
BEGIN
    DECLARE @r varchar(8000)
    SET @r = ''
    SELECT @r = @r + '/' +Role
    FROM (select a.AdminID,d.Role from r b inner join PA a on a.RenShiID=b.id 
          inner join Role c on a.AdminID=c.adminID inner join  role d on d.ID=c.RoleID )t
    WHERE AdminID=@AdminID
    RETURN STUFF(@r, 1, 1, '')
END

--调用合并列函数--- 

dbo.Role_Name(1) 


--删除合并列函数--
drop function dbo.Role_Name

方法二:xml path()方法在05之后可用

select id,stuff((select '-' + convert(varchar(4),value)from tb where id=A.id order by id for xml path('')),1,1,'') 
as values
from tb A
group by id

 

 

select top 10 a.ID,a.customerName,a.guideType 
,(stuff((select ',' + guideLine from Line where CHARINDEX(cast(id as varchar),a.guideType)>0 for xml path('')),1,1,''))
from callIn as a order by ID desc

 

posted @ 2017-11-21 13:41  ly77461  阅读(3161)  评论(0编辑  收藏  举报