2015-01-27 60 views
13

Voglio recuperare il parentid di un id, se quel parentid ha un genitore di nuovo recuperarlo, e così via. Tipo di tabella gerarchia.Ottieni tutti i genitori per un figlio

id----parentid 
1-----1 
5-----1 
47894--5 
47897--47894 

Sono nuovo di SQL Server e ha provato, alcune query come:

with name_tree as 
(
    select id, parentid 
    from Users 
    where id = 47897 -- this is the starting point you want in your recursion 
    union all 
    select c.id, c.parentid 
    from users c 
    join name_tree p on p.id = c.parentid -- this is the recursion 
) 
select * 
from name_tree; 

E mi sta dando solo una riga. e voglio anche inserire questi record in una variabile di tabella temporanea. Come posso fare questo. Grazie in anticipo. Ci scusiamo per chiedere la semplice domanda (anche se non a me)

risposta

21

Prova questo per ottenere tutti i genitori di un bambino

;with name_tree as 
(
    select id, parentid 
    from Users 
    where id = 47897 -- this is the starting point you want in your recursion 
    union all 
    select C.id, C.parentid 
    from Users c 
    join name_tree p on C.id = P.parentid -- this is the recursion 
    -- Since your parent id is not NULL the recursion will happen continously. 
    -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to a temp table without CREATE TABLE synthax 
select * 
INTO #TEMP 
from name_tree 
OPTION (MAXRECURSION 0) 

SELECT * FROM #TEMP 

Click here per Visualizzare i risultati

EDIT:

Se vuoi inserire in una variabile di tabella, puoi fare qualcosa del tipo:

-- Declare table varialbe 
Declare @TABLEVAR table (id int ,parentid int) 


;with name_tree as 
(
    select id, parentid 
    from #Users 
    where id = 47897 -- this is the starting point you want in your recursion 
    union all 
    select C.id, C.parentid 
    from #Users c 
    join name_tree p on C.id = P.parentid -- this is the recursion 
    -- Since your parent id is not NULL the recursion will happen continously. 
    -- For that we apply the condition C.id<>C.parentid 
    AND C.id<>C.parentid 
) 
-- Here you can insert directly to table variable 
INSERT INTO @TABLEVAR 
select * 
from name_tree 
OPTION (MAXRECURSION 0) 

SELECT * FROM @TABLEVAR 

Click here per visualizzare il risultato

0

La query sta eseguendo la ricorsione ma in direzione opposta. Quindi, se si cambia punto di partenza per:

where id = 1 

allora avrete utente 1 e tutti i suoi successori

0

non ha menzionato l'uscita e l'ingresso desiderato. Tuttavia si può provare in questo modo,

Declare @t table (id int ,parentid int) 
insert into @t 
select 1,1 union all 
select 5,1 union all 
select 47894,5 union all 
select 47897,47894 

;With CTE as 
(
select * from @t where id=1 
union all 
Select a.* from @t a inner join cte b 
on b.id=a.parentid and 
a.id<>b.id 
) 
select * from cte 
Problemi correlati