Using COALESCE function to make values separated with commas

后端 未结 4 1297
走了就别回头了
走了就别回头了 2020-11-28 08:14

I have a table (EMP) I know that using the COALESCE function we can get the values of any column in this way

23,23,45,34

SELECT          


        
4条回答
  •  鱼传尺愫
    2020-11-28 08:48

    Description

    dknaack solution has some drawbacks when text contains some XML caracters like <, which are html-entitized as <. This can be solved using the TYPE directive which sends the response as xml, then extract the raw value as string.

    There are plenty more solutions to the problem in this article : Concatenating Row Values in T-SQL

    Sample

    SELECT STUFF((
        select ','+ cast(OfferID as nvarchar(255)) 
        from Emp b
        WHERE a.EmpID= b.EmpID
        FOR XML PATH(''), TYPE
        ).value('.', 'varchar(max)')
        ,1,1,'') AS COLUMN2
    FROM Emp a
    GROUP BY a.EmpID
    

提交回复
热议问题