No one expects the Spanish Inquisition of hierarchies. These days, when I see an org structure (like the one you have here), I refer to the HierarchyId data type. Essentially, it allows you to answer questions such as βwhat value (s) is under thisβ? And βwhat value does this belong to?β Here's how I implement it:
alter table dbo.Employee add OrgStructure HierarchyId null; with h as ( select EmployeeId, SupervisorId, '/' + cast(EmployeeId as varchar) + '/' as h from dbo.Employee as e where e.SupervisorId is null --employees w/oa supervisor union all select e.EmployeeId, e.SupervisorId, hh + '/' + cast(EmployeeId as varchar) + '/' from dbo.Employee as e join h on e.SupervisorId = h.SupervisorId ) update e set OrgStructure = hh from dbo.Employee as e join h on e.EmployeeId = h.EmployeeId; create index [IX_Employee_OrgStructure] on dbo.Employee (OrgStructure)
Now that the heavy lift is done, in fact the answer to your problem is trivial:
select * from dbo.Employee as supervisor join dbo.Employee as reports on reports.OrgStructure.IsDescendantOf(supervisor.OrgStructure) where supervisor.EmployeeId = 1
The advantage that I see is that you do not calculate the hierarchy on the fly every time you need to answer this question. You do it once, and you're done.
source share