I have a Employee table like
emp_id bigint,
reports_to bigint,
emp_name varchar(20),
Constraint [PK_Emp] Primary key (emp_id),
Constraint [FK_Emp] Foreign key (r
Using Common_Table_Expression we can write like this
WITH Employee_CTE(employeeid,hierarchy_level,name) AS
(
SELECT employeeid,1 as level,name from employee where employeeid=1
UNION ALL
SELECT e.employeeid,level +1, e.name
from employee e
INNER JOIN Employee_CTE c ON e.employeeid = c.managerid
)
SELECT * FROM Employee_CTE order by employeeid
You could use a recursive CTE:
; with CTE as
(
select emp_id
, reports_to
, emp_name
, 1 as level
from Emp
where emp_name = 'Sumanta'
union all
select child.emp_id
, child.reports_to
, child.emp_name
, level + 1
from Emp child
join CTE parent
on child.reports_to = parent.emp_id
)
select *
from CTE
Example at SQL Fiddle.