Hi @VDT-7677,
You’re very close the issue is only in the upward move (e.g., 5 → 4) logic.
Right now it updates too many rows, which is why you see gaps (missing 6, ending at 11).
Fix (only change needed)
Update your UPWARD shift logic to restrict the range:
;WITH MoveUp AS
(
SELECT i.TestID,
i.Sort AS NewSort,
d.Sort AS OldSort
FROM inserted i
INNER JOIN deleted d ON i.TestID = d.TestID
WHERE i.Sort < d.Sort
)
UPDATE t
SET t.Sort = t.Sort + 1
FROM dbo.Test t
INNER JOIN MoveUp m
ON t.Sort >= m.NewSort
AND t.Sort < m.OldSort -- key fix
WHERE t.TestID <> m.TestID;
this works because
For Yellow (5 → 4):
- Only Grey (4) shifts to 5
- No extra rows affected
- No gaps, no overflow
Downward logic is already correct Sort = -1 → MAX(Sort)+1 logic is fine
In short limit the update to NewSort <= Sort < OldSort that fixes your Scenario 1 completely.
Thanks,
Akhil.