如何获取所有父名称

时间:2012-01-20 12:29:52

标签: sql sql-server-2008 tsql hierarchy

请查看查询。 我想开发一个查询,当我给出一个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

3 个答案:

答案 0 :(得分: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 
;

---享受

答案 1 :(得分: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 :(得分: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