让所有父母为孩子

sri*_*cle 21 t-sql sql-server recursion hierarchy recursive-cte

我想检索一个id的parentid,如果那个parentid有一个父母再次检索它,依此类推.一种层次表.

id----parentid
1-----1
5-----1
47894--5
47897--47894
Run Code Online (Sandbox Code Playgroud)

我是sql server的新手并试过,有些查询如下:

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;
Run Code Online (Sandbox Code Playgroud)

它只给我一排.我还想将这些记录插入临时表变量中.我怎样才能做到这一点.提前致谢.很抱歉问这个简单的问题(虽然不是我)

Sar*_*avu 28

试着这个让所有孩子的父母

;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
Run Code Online (Sandbox Code Playgroud)

点击这里查看结果

编辑:

如果要插入表变量,可以执行以下操作:

-- 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
Run Code Online (Sandbox Code Playgroud)

点击这里查看结果