2015-01-27 21 views
13

Tôi muốn truy xuất parentid của id, nếu parentid đó có cha mẹ lần nữa truy xuất nó, v.v. Loại bảng phân cấp.Nhận tất cả cha mẹ cho con

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

sáng mới đến máy chủ sql và cố gắng, một số truy vấn như:

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; 

Nó được đem lại cho tôi chỉ có một hàng. và tôi cũng muốn chèn các bản ghi này vào một biến bảng tạm thời. Làm cách nào tôi có thể thực hiện việc này. cảm ơn trước. xin lỗi vì đặt câu hỏi đơn giản (mặc dù không phải với tôi)

Trả lời

21

Hãy thử điều này để có được tất cả các bậc cha mẹ của một đứa trẻ

;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 để xem kết quả

EDIT:

Nếu bạn muốn chèn vào biến bảng, bạn có thể làm điều gì đó như:

-- 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 để xem kết quả

0

Truy vấn của bạn đang thực hiện đệ quy nhưng theo hướng ngược lại. Vì vậy, nếu bạn thay đổi bắt đầu từ điểm đến:

where id = 1 

sau đó bạn sẽ phải sử dụng 1 và tất cả các người kế vị ông

0

bạn không đề cập đến kết quả mong muốn và đầu vào. Tuy nhiên, bạn có thể thử như thế này,

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 
Các vấn đề liên quan