我使用A节中的查询来实现B节中的屏幕截图。但我真正想要做的是在C部分中显示。
A部分:
SELECT
Id, DepartmentName,
CAST(0 AS INT) AS 'ParentID',
CAST(DepartmentName AS VARCHAR(1000)) AS ' '
FROM Departments
WHERE ParentID = 0
UNION ALL
SELECT
t2.Id, t2.DepartmentName, t2.ParentID,
CAST(g.DepartmentName + ' > ' + t2.DepartmentName AS VARCHAR(1000))
FROM Departments t2
INNER JOIN Departments g ON t2.ParentID = g.Id
B节:
C节:
原始表输出:
答案 0 :(得分:1)
递归CTE,几乎与您现有的查询相同:
;WITH x as (
SELECT
Id, DepartmentName,
CAST(0 AS INT) AS 'ParentID',
CAST(DepartmentName AS VARCHAR(1000)) AS fullname
FROM Departments
WHERE ParentID = 0
UNION ALL
SELECT
t2.Id, t2.DepartmentName, t2.ParentID,
CAST(g.fullname + ' > ' + t2.DepartmentName AS VARCHAR(1000))
FROM Departments t2
INNER JOIN x g ON t2.ParentID = g.Id
)
SELECT * FROM x