如何将 T-SQL CTE 查询中的唯一标识符 ID 组合成字符串

How to combine uniqueidentifier IDs in T-SQL CTE query into string

我想在 T-SQL CTE 查询中用逗号分隔的字符串构建 uniqueidentifier ID:

WITH departmentcte(ID, Name, ParentID, LEVEL, FullPath) AS
( 
    SELECT 
        ID, Name, ParentID, 0 AS LEVEL, 
        CAST(Name AS VARCHAR(1024)) AS FullPath 
    FROM 
        ItemModels 
    WHERE 
        ParentID IS NULL

    UNION ALL  

    SELECT 
        d.ID, d.Name, d.ParentID, departmentcte.LEVEL + 1 AS LEVEL,
        CAST(departmentcte.FullPath + '\' + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath  
    FROM 
        ItemModels d
    INNER JOIN 
        departmentcte ON departmentcte.ID = d.ParentID
)
SELECT ID, Name, FullPath  
FROM departmentcte;

它returns这个结果符合预期:

但我想获取像

这样的子集的所有 ID

所以我尝试按照查询进行操作,但出现错误

Type mismatch between the bind and recursive parts in the "SubIDs" column of the recursive "departmentcte" query.

WITH departmentcte(ID, Name, ParentID, LEVEL, FullPath, SubIDs) AS
( SELECT ID, Name, ParentID, 0 AS LEVEL, CAST(Name AS VARCHAR(1024)) AS FullPath, 
    convert(nvarchar(36), ID) as SubIDs FROM ItemModels WHERE ParentID IS NULL
 UNION ALL  
 SELECT d.ID, d.Name, d.ParentID, departmentcte.LEVEL + 1 AS LEVEL,
      CAST(departmentcte.FullPath + '\' + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath,    
      ( ISNULL(departmentcte.SubIDs,'') + '\' + convert(nvarchar(36), d.ID) )  AS SubIDs 
 FROM ItemModels d
      INNER JOIN departmentcte ON departmentcte.ID = d.ParentID)
SELECT ID, FullPath, SubIDs  FROM departmentcte;

正如我所见,SubID 具有 nvarchar 数据类型,那么问题出在哪里?

感谢所有我找到了解决方案

    WITH departmentcte(ID,ParentID, LEVEL, FullPath, SubIDs) AS
    ( SELECT ID,  ParentID, 0 AS LEVEL, CAST(Name AS VARCHAR(1024)) AS FullPath, convert(varchar(2048), ID) as SubIDs 
        FROM ItemModels WHERE ParentID IS NULL
     UNION ALL  
     SELECT d.ID,  d.ParentID, departmentcte.LEVEL + 1 AS LEVEL, 
          CAST(        departmentcte.FullPath  + ','  + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath,      
          CAST( ISNULL(departmentcte.SubIDs,'') + ',' + convert(nvarchar(36), d.ID)  AS VARCHAR(2048))  AS SubIDs 
     FROM ItemModels d INNER JOIN departmentcte ON departmentcte.ID = d.ParentID)

SELECT *  FROM departmentcte;

想法是在 UNION ALL 的两个字段中使用相同大小的 varchar/nvarchar。 在我的例子中是 varchar(2048)