Try the following (btw. you really should consider an upgrade ;)
CREATE TRIGGER trg_Test_AdjustSort
ON dbo.Test
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- Handle only if Sort column was inserted/updated
-- Determine minimum sort per affected value
;WITH SortedInserted AS
(
SELECT DISTINCT Sort
FROM inserted
)
UPDATE t
SET t.Sort = t.Sort + si.Increment
FROM dbo.Test t
INNER JOIN
(
SELECT si.Sort, COUNT(*) AS Increment
FROM SortedInserted si
CROSS APPLY (SELECT COUNT(*) FROM dbo.Test t2 WHERE t2.Sort >= si.Sort) c
GROUP BY si.Sort
) si ON t.Sort >= si.Sort
WHERE t.TestID NOT IN (SELECT TestID FROM inserted); -- avoid updating the newly inserted/updated rows
END
GO
If the table currently looks like this:
| TestID | Value | Sort |
|---|---|---|
| 1 | Orange | 1 |
| 2 | Red | 2 |
| 3 | Purple | 3 |
and you insert:
INSERT INTO dbo.Test (Value, Sort) VALUES ('NewColor', 2);
the result should look like this:
| TestID | Value | Sort |
|---|---|---|
| 1 | Orange | 1 |
| 2 | Red | 3 |
| 3 | Purple | 4 |
| 11 | NewColor | 2 |
Note that with large tables, frequent updates can be expensive. Consider indexing Sort.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin