Comma separated results in SQL

后端 未结 5 1164
我寻月下人不归
我寻月下人不归 2020-11-22 03:24

I have the following code which will create a comma delimited list for my results:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+\', \' ,         


        
5条回答
  •  终归单人心
    2020-11-22 03:48

    Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

    SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
                FROM EDUCATION EE
                WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
                ORDER BY sortOrder
            FOR XML PATH('')), 1, 1, '') AS listStr
    
    FROM EDUCATION E
    GROUP BY E.STUDENTNUMBER
    

    Here is the FIDDLE

提交回复
热议问题