【发布时间】:2023-03-10 20:45:01
【问题描述】:
该应用程序是为一个员工ID获取所有经理
declare @emp table (id int primary key, mgr int);
insert into @emp values
(1, null)
, (2, 1)
, (3, 2)
, (4, null)
, (5, 4);
select * from @emp;
; with cte as
( select e.id, e.mgr, cnt = 1
from @emp e
union all
select e.id, e.mgr, cnt + 1
from @emp e
join cte
on cte.mgr = e.id
)
select id, mgr, cnt
from cte
where id = 3;
上面只返回 id = 3 的单行。我知道这是预期的,但不是我想要的。我想从 3 点开始(锚定)并获得经理链。
如果我对锚点进行硬编码,我会得到想要的结果。
见下文:
; with cte as
( select e.id, e.mgr, cnt = 1
from @emp e
where e.id = 3
union all
select e.id, e.mgr, cnt + 1
from @emp e
join cte
on cte.mgr = e.id
)
select id, mgr, cnt
from cte;
我的问题是如何仅在 cte 上的 where 中分配锚点(顶部)?
如果不在where 中,是否还有另一种方法可以仅分配锚点(而不是 cte 中的硬编码)?
【问题讨论】:
标签: sql sql-server tsql recursion common-table-expression