How to close sequence gaps in SQL Server?

后端 未结 4 1117
囚心锁ツ
囚心锁ツ 2021-01-22 20:02

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           


        
4条回答
  •  孤独总比滥情好
    2021-01-22 21:05

    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
    

提交回复
热议问题