2012-12-13 6 views
12

Ich habe Struktur wie folgt aus:

Wie alle Kinder eines Elternteils zu bekommen und ihre Kinder dann in Abfrage mit Rekursion

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

Diese Struktur verfügt über 3 Ebenen: Hauptgerät, Untereinheitenund SubSubUnits.

Ich möchte alle Kinder von UnitId auswählen.
Wenn ich nach Einheit suche, muss ich alle Baum bekommen.
Wenn ich nach SubUnit1 suche, muss ich SubUnit1 und alle Kinder von SubUnit1 bekommen.
Wenn ich SubSubUnit2 suche, muss ich mich selbst holen.

Hier ist mein Versuch:

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 

Ich benutze 3 gewerkschafts Worten, es ist nicht gut, aber es funktioniert. Fallstruktur wird N Ebenen haben, wie muss ich das richtige Ergebnis bekommen?

+0

Werfen Sie einen Blick auf diese Antwort: http://stackoverflow.com/questions/317322/optimized-sql-for-tree-structures – twoleggedhorse

Antwort

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 auf SQLFiddle

+0

Es funktioniert! Danke! – user1893999

+0

Danke. Dieser Code ist Arbeit. – Datta