2012-01-20 50 views
1

請參閱查詢。 我想開發一個查詢,其中當我給一個ID 我需要遞歸地獲取所有的名字。例如 當我給3我應該得到的名字客戶,設置和管理 我需要得到它,而不使用臨時表和遊標。 在此先感謝您的幫助。如何獲取所有父母姓名

DECLARE @tblPagePath TABLE 
         (id int, 
         name varchar(100), 
         pid int); 

INSERT INTO @tblPagePath 
     (id, name, pid) 
VALUES (1, -- id - int 
      'Admin', -- name - varchar(100) 
      null -- pid - int 
     ) 
INSERT INTO @tblPagePath 
     (id, name, pid) 
VALUES (2, -- id - int 
      'Setup', -- name - varchar(100) 
      1 -- pid - int 
     )      

INSERT INTO @tblPagePath 
     (id, name, pid) 
VALUES (3, -- id - int 
      'Customer', -- name - varchar(100) 
      2 -- pid - int 
     );  



SELECT * 
FROM @tblPagePath 
+0

SQL Server 2008中 – Gopu

回答

0
WITH C AS 
(
    SELECT T.id, 
     T.name, 
     T.pid 
    FROM @tblPagePath AS T 
    WHERE T.id = 3 
    UNION ALL 
    SELECT T.id, 
     T.name, 
     T.pid 
    FROM @tblPagePath AS T 
    INNER JOIN C 
     ON C.pid = T.id 

) 
SELECT * 
FROM C 
--WHERE C.id <> 3 
1

假設的SQLServer:

;with cte as (select id, id pid from @tblPagePath a 
       where not exists (select null from @tblPagePath c 
           where a.id=c.pid) 
       union all 
       select c.id, t.pid 
       from @tblPagePath t 
       join cte c on c.pid =t.id) 
select t.id, t.name 
from @tblPagePath t 
join cte c on t.id = c.pid and c.id = @id 
2
WITH Parents (ID, pid, Level, Name) 
AS 
(
    SELECT ID 'ID', 
     pid 'ParentId', 
     1 as level, 
     Name 'Name' 
    FROM tblPagePath 
    WHERE ID = 3 
    UNION ALL 
    SELECT j.ID 'ID', 
      j.pid 'ParentId', 
      Level + 1, 
      j.Name 'Name' 
    FROM tblPagePath as j 
    INNER JOIN Parents AS jpt ON j.ID = jpt.pid 
) 
SELECT * 
FROM Parents 
; 

---享受