我想检索一个id的parentid,如果那个parentid让父母再次检索它,依此类推。 层次结构表的种类。
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;
它只给我一排。 我还想将这些记录插入临时表变量中。 我怎样才能做到这一点。提前致谢。很抱歉问这个简单的问题(虽然不是我)
答案 0 :(得分:26)
尝试这样做以获得孩子的所有父母
;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查看结果
编辑:
如果要插入表变量,可以执行以下操作:
-- 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查看结果
答案 1 :(得分:0)
您的查询正在进行递归,但方向相反。因此,如果您将起点更改为:
where id = 1
然后您将拥有用户1
及其所有后继者
答案 2 :(得分:0)
你没有提到所需的输出和输入。 但是你可以这样试试,
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