2015-01-27 8 views
13

Ich möchte die Parent-ID einer ID abrufen, wenn diese Eltern-ID ein Elternteil wieder abrufen, und so weiter. Art der Hierarchietabelle.Erhalten Sie alle Eltern für ein Kind

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

bin neu in SQL Server und versucht, einige Anfragen wie:

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; 

Es ist mir nur eine Zeile zu geben. und auch ich möchte diese Datensätze in eine temporäre Tabellenvariable einfügen. Wie kann ich das tun? Danke im Voraus. sorry für die einfache Frage zu stellen (obwohl mir nicht)

Antwort

21

dies versuchen, alle Eltern eines Kindes

;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 sehen führen

EDIT zu erhalten:

Wenn Sie Möchten Sie in eine Tabellenvariable einfügen, können Sie Folgendes tun:

-- 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 zum Anzeigen des Ergebnisses

0

Ihre Abfrage führt eine Rekursion durch, jedoch in umgekehrter Richtung. Also, wenn Sie zum Startpunkt ändern:

where id = 1 

dann werden Sie haben Benutzer 1 und alle seine Nachfolger

0

Sie den gewünschten Ausgang und Eingang nicht erwähnt. Allerdings können Sie versuchen,

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