1

我想uniqueidentifier在 T-SQL CTE 查询中构建用逗号分隔为字符串的 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;

它按预期返回此结果:

在此处输入图像描述

但我想获得一个子集的所有ID,比如

在此处输入图像描述

所以我尝试下面的查询,我得到了错误

在递归“departmentcte”查询的“SubIDs”列中键入绑定和递归部分之间的不匹配。

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;

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

4

1 回答 1

2

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

    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;

这个想法是varchar/nvarcharUNION ALL. 就我而言,它是varchar(2048)

于 2020-08-19T04:40:39.930 回答