SQL结果以逗号水平分隔

时间:2018-11-04 11:18:58

标签: sql sql-server sql-server-2014

我有以下代码,如何为结果创建逗号分隔列表:

查询:

SELECT  
    STUFF((SELECT  ',' + Task_ID
           FROM Tasks EE
           WHERE EE.Task_ID = E.Task_ID  
             AND E.Task_Loc = '8'
           FOR XML PATH('')), 1, 1, '') AS TaskList
FROM 
    Task E
WHERE  
    E.Task_Loc = '8'

我的查询结果:

SER.011
WAS.002

预期结果:

SER.011, WAS.002 

1 个答案:

答案 0 :(得分:1)

您的代码应该基本正确:

SELECT STUFF((SELECT  ',' + CONVERT(VARCHAR(MAX), Task_ID)
              FROM Tasks EE
              WHERE EE.Task_Loc = '8'
              FOR XML PATH('')
             ), 1, 1, '') AS TaskList