简体   繁体   English

SQL Server中的父子关系

[英]Parent Child relation in SQL Server

I have a table with this structure: 我有一个这种结构的表:

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

Let me explain the scenario, when we renew a project we treat this as a new project and enter it under its parent project. 让我解释一下这个场景,当我们更新项目时,我们将其视为一个新项目并在其父项目下输入。

Like 102 is child project of its parent 102 and child 103's parent is 102 and so on. 如102是其父102的子项目,而子103的父项是102,依此类推。

Now, my question is to find out the grand parent, parent and child. 现在,我的问题是要找出父母,父母和孩子。

Like in above case 101 is grand parent of 102,103 and 104. And 102 is parent of 103 and 104. 与上述情况类似,101是102,103和104的祖父.102是103和104的父亲。

So, I want my result as: 所以,我希望我的结果如下:

(If I pass 101 as parameter of ParentProjectID ) (如果我将101作为ParentProjectID参数传递)

ParentProjectID  ChildProjectID
      101             102
      101             103
      101             104

Any help will be appreciated. 任何帮助将不胜感激。

You can use recursive common table expression: 您可以使用递归公用表表达式:

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 sql小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM