如何使用T-sql递归查询显示自身和子项的父ID

时间:2014-03-26 09:49:58

标签: sql sql-server tsql recursion

我正在处理带有父子关系的表的递归查询

ID | ParentID | description
1 | null | Company
2 | 1 | Department
3 | 2 | Unit1
4 | 2 | Unit2
5 | 4 | Unit3
6 | 4 | Unit4

并且假设显示以下结果:

ID | ParentID | description
1 | null | Company
2 | 2 | Department
3 | 2 | Unit1
4 | 2 | Unit2
5 | 2 | Unit3
6 | 2 | Unit4

当然,Deparments和单位的数量更大。基本任务是显示父级及其子级别的parentId。你对如何实现这个有什么想法吗?

到目前为止,我只进行了此次查询

WITH cte (ID, ParentID, description)
AS
(
    SELECT ID, ParentID, description
    FROM T1
  UNION ALL
    SELECT  e.ID, e.ParentID, e.description
    FROM T2 AS e
    JOIN cte ON e.ID = cte.ParentID

)
 SELECT 
 cte.ID, cte.ParentID, cte.description
FROM cte
cte.ParentID is not null

1 个答案:

答案 0 :(得分:1)

你的语法不是很正确,但这个想法是正确的。最后,您希望获取父父的父级为NULL的行。这可能有效(未经测试):

WITH cte(ID, ParentID, description, lev) AS
      (SELECT ID, ParentID, description, 1 as lev
       FROM table T1
       UNION ALL
       SELECT  cte.ID, e.ParentID, cte.description, cte.lev + 1
       FROM table e JOIN 
            cte
            ON e.ID = cte.ParentID
     )
SELECT cte.ID, cte.ParentID, cte.description
FROM cte left outer join
     table t
     on cte.ParentId = t.ParentId     
WHERE t.ParentID is null;