如何在查询中使用递归获取父项的所有子项,然后获取其子项

use*_*999 17 tree recursive-query sql-server-2008

我有这样的结构:

<Unit>
  <SubUnit1>
           <SubSubUnit1/>
           <SubSubUnit2/>
           ...
           <SubSubUnitN/>
  </SubUnit1/>
  <SubUnit2>
           <SubSubUnit1/>
           <SubSubUnit2/>
           ...
           <SubSubUnitN/>
  </SubUnit2/>
  ...
  <SubUnitN>
           <SubSubUnit1/>
           <SubSubUnit2/>
           ...
           <SubSubUnitN/>
  </SubUnitN/>
</Unit>
Run Code Online (Sandbox Code Playgroud)

这个结构有3个级别:主单元,SubUnits和SubSubUnits.

我想通过UnitId选择所有孩子.
如果我按单位搜索,我必须得到所有树.
如果我通过SubUnit1搜索,我必须获得SubUnit1和SubUnit1的所有子项.
如果我搜索SubSubUnit2,我必须得到自己.

这是我的尝试:

with a(id, parentid, name)
as (
select id, parentId, name
   from customer a
   where parentId is null 
union all
   select a.id, a.parentid, a.Name
   from customer
     inner join a on customer.parentId = customer.id
    )
select parentid, id, name 
from customer pod
where pod.parentid in (
select id
from customer grbs
where grbs.parentid in (
select id
from customer t
where t.parentid = @UnitId
))
union 
select parentid, id, name
from customer grbs
where grbs.parentid in (
select id
from customer t
where t.parentid = @UnitId
)
union
select parentid, id, name
from customer c
where c.Id = @UnitId
order by parentid, id
Run Code Online (Sandbox Code Playgroud)

我使用3个联合词,它不是很好但是它有效.案例结构将有N个级别,我如何获得正确的结果?

Ale*_*nko 35

DECLARE @Id int = your_UnitId
;WITH cte AS 
 (
  SELECT a.Id, a.parentId, a.name
  FROM customer a
  WHERE Id = @Id
  UNION ALL
  SELECT a.Id, a.parentid, a.Name
  FROM customer a JOIN cte c ON a.parentId = c.id
  )
  SELECT parentId, Id, name
  FROM cte
Run Code Online (Sandbox Code Playgroud)

SQLFiddle上演示