您可能应该使用递归CTE而不是WHILE
循环来查找所有员工。我没有你的表格或数据,所以我做了一些:
create table Employees (
ID int not null primary key,
Name varchar(20) not null,
BigBossID int null foreign key references Employees(ID),
Salary decimal(18,4) not null
)
go
insert into Employees (ID,Name,BigBossID,Salary) values
(1,'Joe',2,2.50),
(2,'Robert',3,19000.75),
(3,'Michelle',null,1234567890.00)
然后我可以使用这个查询来查找 Michelle 下面的所有员工:
declare @RootID int
set @RootID = 3
;With EmployeesBelowRoot as (
select ID from Employees where BigBossID = @RootID
union all
select e.ID from Employees e inner join EmployeesBelowRoot ebr on e.BigBossID = ebr.ID
)
select SUM(Salary) from Employees where ID in (select ID from EmployeesBelowRoot)
您可以(如果您认为值得)将 CTE ( EmployeesBelowRoot
) 放入 UDF 中并将其@RootID
作为参数调用,但我现在只是将其直接放在查询中。