Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Holen Sie sich alle Eltern für ein Kind

Versuchen Sie dies, um alle Eltern eines Kindes zu erhalten

;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

Klicken Sie hier, um das Ergebnis anzuzeigen

BEARBEITEN :

Wenn Sie in eine Tabellenvariable einfügen möchten, 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

Klicken Sie hier, um das Ergebnis anzuzeigen