Jak uzyskać wszystkie dzieci rodzica, a następnie ich dzieci, używając rekurencji w zapytaniu
Mam taką strukturę:
<Unit>
<SubUnit1>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit1/>
<SubUnit2>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit2/>
...
<SubUnitN>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnitN/>
</Unit>
Ta struktura ma 3 poziomy: jednostkę główną, jednostki podrzędne i jednostki podrzędne.
Chcę wybrać wszystkie dzieci według UnitId.
Jeśli szukam według jednostki, muszę zdobyć wszystkie drzewa.
Jeśli szukam według SubUnit1, muszę uzyskać SubUnit1 i wszystkie potomki SubUnit1.
Jeśli przeszukuję SubSubUnit2, muszę się sam zdobyć.
Oto moja próba:
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
Używam 3 słów związku, nie jest dobrze, ale działa. Struktura przypadku będzie miała N poziomów, w jaki sposób muszę uzyskać poprawny wynik?