2015-01-27 32 views
13

Chcę pobrać parentid z identyfikatorem, jeśli to parentid ma rodzica ponownie go pobrać, i tak dalej. Rodzaj tabeli hierarchii.Uzyskaj wszystkich rodziców dla dziecka

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

Jestem nowym serwerem SQL i próbowałem niektóre pytania jak:

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; 

To daje mi tylko jeden wiersz. , a także chcę wstawić te rekordy do tymczasowej zmiennej tabeli. Jak mogę to zrobić. z góry dziękuję. Przepraszam za pytanie proste pytanie (choć nie do mnie)

Odpowiedz

21

Spróbuj tego, aby wszystkie rodzicom dziecka

;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 aby zobaczyć rezultat

EDIT:

Jeśli chcesz wstawić do zmiennej tabeli, możesz zrobić coś takiego:

-- 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 aby zobaczyć wynik

0

Twoje zapytanie wykonuje rekursję, ale w przeciwnym kierunku. Więc jeśli zmienisz punkt wyjścia do:

where id = 1 

następnie trzeba będzie użytkownik 1 i wszyscy jego następcy

0

nie wspomniałeś żądane wyjście i wejście. Możesz jednak wypróbować w ten sposób:

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 
Powiązane problemy