我是递归 CTE 的新手。我正在尝试开发一个 CTE,它将返回每个经理姓名下的所有员工。所以我有两张桌子:people_rv
和staff_rv
People_rv 表包含所有人员,包括经理和员工。Staff_rv
仅包含经理信息。唯一标识符人员值存储在Staff_rv
. Uniqueidentifier 员工值存储在people_rv
. People_rv
包含经理和员工的 varchar 名字和姓氏值。
但是当我运行以下 CTE 时,出现错误:
WITH
cteStaff (ClientID, FirstName, LastName, SupervisorID, EmpLevel)
AS
(
SELECT p.people_id, p.first_name, p.last_name, s.supervisor_id,1
FROM people_rv p JOIN staff_rv s on s.people_id = p.people_id
WHERE s.supervisor_id = '95E16819-8C3A-4098-9430-08F0E3B764E1'
UNION ALL
SELECT p2.people_id, p2.first_name, p2.last_name, s2.supervisor_id, r.EmpLevel + 1
FROM people_rv p2 JOIN staff_rv s2 on s2.people_id = p2.people_id
INNER JOIN cteStaff r on s2.staff_id = r.ClientID
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT first_name + ' ' + last_name FROM people_rv p join staff_rv s on s.people_id = p.people_id
WHERE s.staff_id = cteStaff.SupervisorID) AS Manager
FROM cteStaff
OPTION (MAXRECURSION 0);
我的输出是:
Barbara G 1 Melanie K
Dawn P 1 Melanie K
Garrett M 1 Melanie K
Stephanie P 1 Melanie K
Amanda F 1 Melanie K
Amanda T 1 Melanie K
Stephanie G 1 Melanie K
Carlos H 1 Melanie K
所以它不会比第一级迭代更多。为什么不?Melanie 是最顶层的主管,但最左边一列中的每个人也是主管。所以这个查询也应该返回级别 2。