如何用逗号分隔查询结果

时间:2014-05-28 09:03:53

标签: sql-server select

我使用此查询

 SELECT cn.name from WMCCMCategories cn 
               INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID 
               INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
               INNER JOIN Companies c ON c.companyId = u.companyId
               WHERE c.companyName = 'SOME NAME' 

并返回一列有很多行值。

现在我想获得所有值的一个字符串,但用逗号分隔',' 所以这就是我试过的

  SELECT  STUFF((SELECT ','+   from WMCCMCategories cn 
               INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID 
               INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
               INNER JOIN Companies c ON c.companyId = u.companyId
               WHERE c.companyName = 'SOME NAME' 
              ORDER BY sortOrder
    FOR XML PATH('')), 1, 1, '') AS listStr
 FROM WMCCMCategories cnn Group by cnn.name

但它在From上给了我错误。如何正确编写呢?

2 个答案:

答案 0 :(得分:1)

SELECT  STUFF((SELECT ','+ cn.name  from WMCCMCategories cn 
               INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID 
               INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
               INNER JOIN Companies c ON c.companyId = u.companyId
               WHERE c.companyName = 'SOME NAME' 
              ORDER BY sortOrder
    FOR XML PATH('')), 1, 1, '') AS listStr
 FROM WMCCMCategories cnn Group by cnn.name

答案 1 :(得分:0)

您在+from之间缺少字段名称。