父子关系 - SQL

时间:2014-04-17 10:29:45

标签: sql sql-server sql-server-2012

我使用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节:

enter image description here

C节:

enter image description here

原始表输出:

Original Table Output:

1 个答案:

答案 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