2012-12-13 29 views
12

Mam strukturę tak:

Jak zdobyć wszystkie dzieci rodziców, a potem ich dzieci korzystających rekursji w zapytaniu

<Unit> 
    <SubUnit1> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnit1/> 
    <SubUnit2> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnit2/> 
    ... 
    <SubUnitN> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnitN/> 
</Unit> 

Struktura ta ma 3 poziomy: Main Unit, podjednostek i SubSubUnits.

Chcę wybrać wszystkie dzieci według UnitId.
Jeśli przeszukuję według jednostki, muszę pobrać całe drzewo.
Jeśli wyszukuję według SubUnit1, muszę pobrać SubUnit1 i wszystkie podrzędne dla dzieci SubUnit1.
Jeśli wyszukuję SubSubUnit2, muszę się sam.

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 Unię słowa, to nie jest dobrze, ale to działa. Struktura przypadku będzie miała N poziomów, w jaki sposób muszę uzyskać poprawny wynik?

+0

Spójrz na to odpowiedź: http://stackoverflow.com/questions/317322/optimized-sql-for-tree-structures – twoleggedhorse

Odpowiedz

18
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 

Demo na SQLFiddle

+0

To działa! Dziękuję Ci! – user1893999

+0

Dzięki. Ten kod jest działaniem. – Datta