I have the following employee table and there is a foreign key relationship between EmpID
and ManagerID
.
Employee Table
Desired Output
I would like to be able to display the employee names in hierarchical order separated by >
from top most manager to the bottom level with the EmpID being the ID of employee at the bottom of the hierarchy.
I know I can get the desired output by joining the table to itself using the following SQL.
select e1.empID, e1.DeptID, e2.Name + ' > ' + e1.Name as Description
from employee e1
left join employee e2
on e1.managerId = e2.empId
I also know that I can add more left joins to the above query to get the desired output. But there is no limit to how deep the hierarchy can be so I guess it will need to be done dynamically.
Any help would be greatly appreciated