Let\'s say I have a Turtle table. When I run
SELECT * FROM Turtle ORDER BY Sort
I get this:
Id | Name | Sort
2 Leo 1
3
Here's the answer I came up with:
UPDATE t
SET t.Sort = t2.Sort
FROM Turtle AS t,
(SELECT Id, Sort = ROW_NUMBER() OVER(ORDER BY Sort) FROM Turtle) as t2
WHERE t.Id = t2.Id
We can select the Turtle table as t2, ordering the turtles by the Sort column, but assigning the ROW_NUMBER() to the Sort column. We can then use the new value in t2.Sort to update each row in the Turtle table where the Ids match.
Edit (based on Juan Carlos Oropeza's feedback):
Here is the code using an explicit JOIN instead.
UPDATE t
SET t.Sort = t2.Sort
FROM Turtle AS t
JOIN (SELECT Id, ROW_NUMBER() OVER(ORDER BY Sort) AS Sort FROM Turtle) AS t2 ON t.Id = t2.Id