Search code examples
sqlsql-serversql-server-2008sql-server-2008r2-express

SQL Qry required to get a comma separated string from a table


In my database there is a table with values below

image attachedenter image description here

In need a qry to get the result like this

enter image description here


Solution

  • DECLARE @TAB TABLE(SIDS INT,VALUE VARCHAR(10))
    
    INSERT INTO @TAB
    
    SELECT 1,'ASC'
    UNION ALL
    SELECT 1,'ASC'
    UNION ALL
    SELECT 1,'ASC'
    UNION ALL
    SELECT 2,'SDF'
    UNION ALL
    SELECT 2,'SFD'
    UNION ALL
    SELECT 3,'ERF'
    UNION ALL
    SELECT 3,'ERF1'
    
    
    SELECT T1.SIDS,VALUE = STUFF((SELECT ','+T2.VALUE FROM @TAB T2 WHERE T1.SIDS = T2.SIDS FOR XML PATH('')),1,1,'')
    FROM @TAB T1
    GROUP BY T1.SIDS
    

    OUTPUT

    SIDS    VALUE
    1   ASC,ASC,ASC
    2   SDF,SFD
    3   ERF,ERF1