【问题标题】:Parent Child relation in SQL ServerSQL Server 中的父子关系
【发布时间】:2013-09-21 15:42:16
【问题描述】:

我有一个这样结构的表:

ParentProjectID  ChildProjectID
------------------------------    
     101             102
     102             103
     103             104
     201             202
     202             203

让我解释一下场景,当我们更新一个项目时,我们将其视为一个新项目并将其输入到其父项目下。

like 102 是其父 102 的子项目,子 103 的父项目是 102,依此类推。

现在,我的问题是找出祖父母、父母和孩子。

如上例 101 是 102,103 和 104 的祖父母。而 102 是 103 和 104 的父母。

所以,我希望我的结果为:

(如果我将 101 作为 ParentProjectID 的参数传递)

ParentProjectID  ChildProjectID
      101             102
      101             103
      101             104

任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server tsql parent-child


    【解决方案1】:

    可以使用递归公用表表达式:

    create procedure usp_Descendants
    (
      @ParentProjectID int
    )
    as
    begin
        ;with cte as (
             select
                 T.ChildProjectID
             from Table1 as T
             where T.ParentProjectID = @ParentProjectID
             union all
             select
                 T.ChildProjectID
             from cte as c
                 inner join Table1 as T on T.ParentProjectID = c.ChildProjectID
        )
        select
            @ParentProjectID, c.ChildProjectID
        from cte as c
    end
    
    exec usp_Descendants @ParentProjectID = 101;
    -----------
    101     102
    101     103
    101     104
    
    exec usp_Descendants @ParentProjectID = 101;
    -----------
    102     103
    102     104
    

    sql fiddle demo

    【讨论】:

    • @DeepakSharma 没问题,递归 cte 功能很强大
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    相关资源
    最近更新 更多