4

给定下表:

create table TreeNode
(
  ID int not null primary key,
  ParentID int null foreign key references TreeNode (ID)
)

我如何编写一个公用表表达式从根(WHERE ParentID IS NULL)开始并遍历其后代,直到结果集包含某个目标节点(例如,WHERE ID = n)?从目标节点开始并向上遍历到根节点很容易,但这不会生成相同的结果集。具体来说,不包括与目标节点具有相同父节点的节点。

我的第一次尝试是:

with Tree as
(
  select
    ID,
    ParentID
  from
    TreeNode
  where
    ParentID is null
  union all select
    a.ID,
    a.ParentID
  from
    TreeNode a
    inner join Tree b
      on b.ID = a.ParentID
  where
    not exists (select * from Tree where ID = @TargetID)
)

这给出了错误:Recursive member of a common table expression 'Tree' has multiple recursive references.

注意:我只对自上而下的遍历感兴趣。

4

1 回答 1

1

更新 2:

第三次尝试在两个方向上“遍历”树。

构建一个ParentIDsTarget到的 CTE root。然后,从短列表中显示的tree或中选择。nodesIDParent

--
;
WITH    Tree
          AS ( SELECT   ID
                       ,ParentID
               FROM     TreeNode
               WHERE    [ID] = @targetId
               UNION ALL
               SELECT   a.ID
                       ,a.ParentID
               FROM     TreeNode a
                        INNER JOIN Tree b ON b.ParentID = a.ID
             )
    SELECT  *
    FROM    [dbo].[TreeNode] n
    WHERE  EXISTS (SELECT *
                   FROM [Tree] t
                   WHERE [t].[ID] = [n].[ID]
                         OR [t].[ID] = [n].[ParentID]
                  )
于 2010-10-21T15:42:55.507 回答