次の表を考えます。
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.
注: トップダウンのトラバーサルにのみ関心があります。