The problem goes deeper than this, you want to avoid any loops on your chart by using the tree efficiently.
I think you better do this at the application level.
UPDATE: But if you prefer to do this with a trigger, see Common Table Expressions (CTE) . You can create a recursive query in a trigger that checks for loops:
create trigger prevent_management_cycles on employee instead of update as declare @found_rows int ;with cycle_detector (employee_id) as ( select employee_id from inserted union all select employee.employee_id from employee join cycle_detector on employee.manager_id = cycle_detector.employee_id ) select @found_rows = count(*) from cycle_detector join inserted on inserted.manager_id = cycle_detector.employee_id if @found_rows > 0 raiserror('cycle detected!', 1, 1) else
Note : it is assumed that employee_id is the primary key, and manager_id is a foreign key pointing to employee.employee_id .
source share