- Trees.DirectReports is a closure (hierarchy) table.
- There is a table called
Users
with:RowID, EmployeeId, and MangerId
.@RowCount
is the number of records in this table and#EmpMgr
is a cursor for this table.
Below is the relevant sql code that I would like to convert from a cursor based operation to a set based operation.
WHILE @RowCount <= @NumberRecords --loop through each record in Users table
BEGIN
SET @EmpId = (SELECT EmployeeId FROM #EmpMgr WHERE RowID = @RowCount)
SET @MgrId = (SELECT ManagerId FROM #EmpMgr WHERE RowID = @RowCount)
INSERT INTO [Trees].[DirectReports](EmployeeId, ManagerId, Depth)
SELECT c.EmployeeId, p.ManagerId, p.Depth + c.Depth + 1
FROM Trees.DirectReports p join Trees.DirectReports c
WHERE p.EmployeeId = @MgrId AND c.ManagerId = @EmpId
SET @RowCount = @RowCount + 1
END
So I'd really like to figure out how to do this as a set query because I know it would be much faster that way but my brain isn't quite making the proper connections today to figure it out.
*Note that to answer this question you will need to already understand how closure tables work. Otherwise the above probably won't make sense.