How to Implement a Hierarchy using SQL Server?

Hierarchy can be implemented using common table expression (CTE).

WITH UserHierarchy ([user_id], [manager_id],[Level]) AS

(

SELECT [user_id],user_ap_mngd_by as manager,0

FROM [user_profile] usrtmp1

WHERE usrtmp1.[user_id]=1

UNION ALL

SELECT usrtmp2.[user_id],user_ap_mngd_by as manager, [Level] + 1

FROM [user_profile] usrtmp2

INNER JOIN UserHierarchy ON

usrtmp2.user_ap_mngd_by = UserHierarchy.[user_id]

)

SELECT * FROM UserHierarchy

Ready to Build
Something
Extraordinary?

Join 300+ companies who trust us to turn their biggest ideas into market-leading solutions.

Our Global Team
500+ Engineers Worldwide
SOC 2 Certified

Get in Touch with Us

Our Global Team
400+ Engineers Worldwide

InApp India Office

121 Nila, Technopark Campus
Trivandrum, Kerala 695581
+91 (471) 277 -1800
mktg@inapp.com

InApp USA Office

999 Commercial St. Ste 210 Palo Alto, CA 94303
+1 (650) 283-7833
mktg@inapp.com

InApp Japan Office

6-12 Misuzugaoka, Aoba-ku
Yokohama,225-0016
+81-45-978-0788
mktg@inapp.com
Terms Of Use
© 2000-2026 InApp, All Rights Reserved