3

我有一个具有这种结构的表:

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

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

比如 102 是其父 102 的子项目,而子 103 的父项目是 102,依此类推。

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

就像上面的情况一样,101 是 102,103 和 104 的祖父母。而 102 是 103 和 104 的父母。

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

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

ParentProjectID  ChildProjectID
      101             102
      101             103
      101             104

任何帮助将不胜感激。

4

1 回答 1

2

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

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

于 2013-09-21T16:12:20.220 回答