Get the hierarchy position
An important problem when dealing with recursion is tracking the level of recursion. In the IT organization, this means keeping track of the position in the hierarchy of each employee.

For this, you will use a LEVEL field which keeps track of the current recursion step. You have to introduce the field in the anchor member, and increment this value on each recursion step in the recursion member.
Keep in mind, the first hierarchy level is 0, the second level is 1 and so on.
Diese Übung ist Teil des Kurses
Hierarchical and Recursive Queries in SQL Server
Anleitung zur Übung
- Initialize the field
LEVELto 1 at the start of the recursion. - Select the information of the IT director as the initial step of the CTE by filtering on
Supervisor. - Set
LEVELto the current recursion step. - Perform a
JOINwith the defined CTE on theIDs of the supervisor and the employee.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
WITH employee_hierarchy AS (
SELECT
ID,
NAME,
Supervisor,
-- Initialize the field LEVEL
___ as LEVEL
FROM employee
-- Start with the supervisor ID of the IT Director
WHERE ___ = ___
UNION ALL
SELECT
emp.ID,
emp.NAME,
emp.Supervisor,
-- Increment LEVEL by 1 each step
___ + 1
FROM employee emp
JOIN employee_hierarchy
-- JOIN on supervisor and ID
ON emp.___ = employee_hierarchy.___)
SELECT
cte.Name, cte.Level,
emp.Name as ManagerID
FROM employee_hierarchy as cte
JOIN employee as emp
ON cte.Supervisor = emp.ID
ORDER BY Level;