28

我想检索一个 id 的 parentid,如果该 parentid 有一个 parent,则再次检索它,依此类推。一种层次结构表。

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

我是 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;

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

4

3 回答 3

45

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

;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

点击这里查看结果

编辑 :

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

-- 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

点击这里查看结果

于 2015-01-27T12:43:25.870 回答
0

您的查询正在进行递归,但方向相反。因此,如果您将起点更改为:

where id = 1

那么您将拥有用户1及其所有继任者

于 2015-01-27T12:56:02.643 回答
0

you didn't mention the desired output and input. However you can try like this,

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
于 2015-01-27T13:09:31.257 回答