ROW_NUMBER() generates incremental integers within each ManagerID partition. In an employee hierarchy, those values can become the next path component when constructing HIERARCHYID values recursively. section 3.3
Numbering employees within manager branches
A temporary table captures each employee and manager, then assigns an incremental value per manager: SELECT EmployeeID, ManagerID, ROW_NUMBER() OVER (PARTITION BY ManagerID ORDER BY ManagerID) AS Incremental INTO #Hierarchy FROM dbo.Employees. A recursive CTE uses Incremental to extend each manager's hierarchy path before updating the Employees table. section 3.3
Use the function here to:
- Create sibling positions separately for each ManagerID. section 3.3
- Consider ROW_NUMBER() as an alternative technique when removing duplicates with DISTINCT causes performance issues. section 5.9
