嗨找到下面的存储过程以按顺序获取名称。
CREATE TABLE emptbl(Emp_id int, Emp_user_id varchar(10), Emp_Name varchar(100), Emp_mgr_id int)
INSERT INTO emptbl
VALUES(1,'D021','Joe',6),
(2,'D024','Kathy',6),
(3,'D054','Shaun',1),
(4,'D058','Tippu',2),
(5,'D059','Paul',4),
(6,'D070','David',9),
(7,'D075','Jack',9)
SELECT * FROM emptbl
CREATE Proc sp_getRepportees
@emp_id varchar(20)
As
--sp_getRepportees 'D070'
DECLARE @min int=1
DECLARE @max int
DECLARE @empout TABLE(Emp_id int, Emp_user_id varchar(10), Emp_Name varchar(100), Emp_mgr_id int)
;WITH CTEEmp(Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id) As
(
SELECT Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id from emptbl where Emp_user_id=@emp_id
UNION ALL
SELECT et.Emp_id,et.Emp_user_id,et.Emp_Name,et.Emp_mgr_id from emptbl et inner join CTEEmp e on et.Emp_mgr_id = e.emp_id)
,CTE2(rno,Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id) as(
SELECT ROW_NUMBER() over (order by emp_id) as rno,* FROM CTEEmp where Emp_user_id<>@emp_id)
select * into #tempe from CTE2
SELECT @max=COUNT(*) from #tempe
select * from #tempe
While(@min<=@max)
begin
IF EXISTS(select Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id from #tempe where Emp_mgr_id in (select Emp_id from #tempe where rno=@min))
begin
INSERT INTO @empout
select Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id from #tempe where rno=@min
union
select Emp_id,Emp_user_id,Emp_Name,Emp_mgr_id from #tempe where Emp_mgr_id in (select Emp_id from #tempe where rno=@min)
end
delete from #tempe where rno=@min
SET @min+=1
end
select Emp_user_id,Emp_Name from @empout