【问题标题】:How to get all parent names如何获取所有父母姓名
【发布时间】:2012-01-20 12:29:51
【问题描述】:

请查看查询。 我想开发一个查询,当我给出一个 id 时 我需要递归地获取所有名称。例如 当我给出 3 时,我应该得到名称 Customer、setup 和 Admin 我需要在不使用临时表和游标的情况下获取它。 提前感谢您的帮助。

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

【问题讨论】:

    标签: sql sql-server-2008 tsql hierarchy


    【解决方案1】:
    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 
    ;
    

    ---享受

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-14
          • 1970-01-01
          • 2021-08-06
          • 1970-01-01
          • 2015-12-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多