SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 hierarchy Level
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

pushp82
Yak Posting Veteran

81 Posts

Posted - 03/05/2013 :  09:32:15  Show Profile  Reply with Quote
Hi Guys,

I got stuck in between of task i.e:
My table is as below(SUB_ID is reference of ID)

ID NAME SUB_ID
1 A 0
2 B 0
3 C 1
4 D 3
5 E 2
6 F 3

I need to get the hierarchy level of ID like
ID NAME LEVEL
1 A 1
2 B 1
3 C 2
4 D 3
5 E 2
6 F 3

How is this possible? Please help

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 03/05/2013 :  09:37:07  Show Profile  Reply with Quote
use recursive ctes


;With CTE
AS
(
SELECT ID,NAME,SUB_ID, CAST(1 AS int) AS Level
FROM table t
LEFT JOIN table t1
On t1.ID = t.SUB_ID
WHERE t1.ID IS NULL

UNION ALL

SELECT t.Id,t.NAME,t.SUB_ID,c.Level+1
FROM CTE c
JOIN table t
ON t.SUB_ID = c.ID
)

SELECT ID,NAME,Level
FROM CTE

OPTION (MAXRECURSION 0)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/


Edited by - visakh16 on 03/05/2013 09:37:31
Go to Top of Page

pushp82
Yak Posting Veteran

81 Posts

Posted - 03/05/2013 :  10:14:44  Show Profile  Reply with Quote
I tried CTE but was not succeed, u r perfect as always thanks visakh
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 03/05/2013 :  10:15:21  Show Profile  Reply with Quote
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.07 seconds. Powered By: Snitz Forums 2000