我想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 数据类型,那么问题出在哪里?