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
Try this
SELECT ID, Name, ROW_NUMBER() OVER(ORDER BY Sort) AS Sort FROM Turtle
You can do the update just using a CTE with the row_number(), and then just update the CTE:
;with CTE as (
select *, row_number () over (order by Sort) as RN
from Turtle
)
update CTE
set Sort = RN
This is what they mean by using a cte in an update.
;WITH cte AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY Sort) NewSort
FROM Turtle
)
UPDATE cte SET Sort = NewSort
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