2013-02-13 16 views
7

Ho seguito gerarchica tabella alberotavolo Utilizzare SQL CTE per includere il percorso e tutti i bambini

GO 
DROP TABLE #tbl 
GO 
CREATE TABLE #tbl (Id int , ParentId int) 
INSERT INTO #tbl (Id, ParentId) VALUES (0, NULL) 
INSERT INTO #tbl (Id, ParentId) VALUES (1, 0) 
INSERT INTO #tbl (Id, ParentId) VALUES (2, 1) 
INSERT INTO #tbl (Id, ParentId) VALUES (3, 1) 
INSERT INTO #tbl (Id, ParentId) VALUES (4, 2) 
INSERT INTO #tbl (Id, ParentId) VALUES (5, 2) 
INSERT INTO #tbl (Id, ParentId) VALUES (6, 3) 
INSERT INTO #tbl (Id, ParentId) VALUES (7, 3) 
GO 

quale mappa to seguente albero

0 
+- 1 
    +- 2 
     +- 4 
     +- 5 
    +- 3 
     +- 6 
     +- 7 

Utilizzando CTE tabella ricorsiva, come posso ottenere il percorso e anche tutti i bambini del nodo selezionato. Per esempio avendo 2 come input, come posso ottenere seguenti dati (ordinato, se possibile)

Id, ParentID 
------- 
0, NULL 
1, 0 
2, 1 
4, 2 
5, 2 

so di poter attraversare su nell'albero (ottenere il percorso), con seguente dichiarazione

WITH RecursiveTree AS (
    -- Anchor 
    SELECT * 
     FROM #tbl 
     WHERE Id = 2 
    UNION ALL 
     -- Recursive Member 
     SELECT Parent.* 
     FROM 
      #tbl AS Parent 
      JOIN RecursiveTree AS Child ON Child.ParentId = Parent.Id 
) 
SELECT * FROM RecursiveTree 

E con seguente dichiarazione, traverse basso nella struttura (ottenere tutti i bambini)

WITH RecursiveTree AS (
    -- Anchor 
    SELECT * 
     FROM #tbl 
     WHERE Id = 2 
    UNION ALL 
     -- Recursive Member 
     SELECT Child.* 
     FROM 
      #tbl AS Child 
      JOIN RecursiveTree AS Parent ON Child.ParentId = Parent.id 
) 
SELECT * FROM RecursiveTree 

Domanda: come combinare questi due comandi in uno?

+1

+1 Per fornire buona spiegazione, DDL, DML e dati di test. –

risposta

4

Basta utilizzare unione di questi due selezionano

SQLFiddle demo

WITH RecursiveTree AS (
    -- Anchor 
    SELECT * 
     FROM #tbl 
     WHERE Id = 2 
    UNION ALL 
     -- Recursive Member 
     SELECT Parent.* 
     FROM 
      #tbl AS Parent 
      JOIN RecursiveTree AS Child ON Child.ParentId = Parent.Id 
), 
RecursiveTree2 AS 
(
    -- Anchor 
    SELECT * 
     FROM #tbl 
     WHERE Id = 2 
    UNION ALL 
     -- Recursive Member 
     SELECT Child.* 
     FROM 
      #tbl AS Child 
      JOIN RecursiveTree2 AS Parent ON Child.ParentId = Parent.id 
) 
select * from 
(
SELECT * FROM RecursiveTree 
union 
SELECT * FROM RecursiveTree2 
) t 
order by id 
Problemi correlati