Gopu
Gopu

Reputation: 55

How to get all parent names

please see the query. i want to develop a query in which when i give an id i need to get all the names recursively. for example when i give 3 i should get the names Customer,setup and Admin i need to get it without using temporarytable and cursors. Thanks in advance for your help.

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

Upvotes: 1

Views: 1454

Answers (3)

user359040
user359040

Reputation:

Assuming 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

Upvotes: 1

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

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

Upvotes: 0

Hiren Visavadiya
Hiren Visavadiya

Reputation: 485

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 
;

--- Enjoy

Upvotes: 2

Related Questions