Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi Frnds,

I have a table with multiple Hierarchy as child relationship.

For eg .:


SQL
ParentId   ChildID

    1             11
    11            21
    21            31
    31            41
    41            51
    51            61
    61            71



I need output as per ChildId and level of Hierarchy...
For example if i pass values in query as ChildId=61 and Hierachy =2

Output Should be


SQL
ParentId    ChildId

   31           41


For example if i pass values in query as ChildId=61 and Hierachy =3

Output Should be

SQL
ParentId    ChildId

  21           31


I tried different ways , but i ddnt get solution.Help me for get solution.


Thanks
Suresh
Posted

1 solution

Tough i am not happy with below solution but this could get you going.

SQL
DECLARE @TBL TABLE
(
	PARENTID INT,
	CHILDID INT
)

DECLARE @TAGERTTBL TABLE
(
	PARENTID INT,
	CHILDID INT,
	Level int IDENTITY(0, 1)
)

INSERT INTO @TBL(PARENTID, CHILDID)
SELECT    1,			 11	UNION ALL
SELECT    11,            21 UNION ALL
SELECT    21,            31 UNION ALL
SELECT    31,            41 UNION ALL
SELECT    41,            51 UNION ALL
SELECT    51,            61 UNION ALL
SELECT    61,            71;

with TMPH(ParentId, ChildID, Level)
AS (
	SELECT ParentID, CHildID, 0 AS level
	FROM   @TBL
	WHERE  PARENTID = 61
	UNION ALL
	SELECT T.ParentId, T.ChildID, Level + 1
	FROM TMPH TM 
	INNER JOIN @TBL T ON TM.ParentId = T.ChildID 
)
INSERT INTO @TAGERTTBL(PARENTID, CHILDID)
SELECT PARENTID, CHILDID FROM TMPH
order by Level desc

SELECT * 
FROM @TAGERTTBL
where Level in (2,3 )
 
Share this answer
 
Comments
Herman<T>.Instance 8-Sep-14 7:25am    
a Common Table Expression is indeed the way to tackle these datarequests

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900