How to close sequence gaps in SQL Server?

后端 未结 4 1078
囚心锁ツ
囚心锁ツ 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 20:55

    Try this

    SELECT ID, Name, ROW_NUMBER() OVER(ORDER BY Sort) AS Sort FROM Turtle
    
    0 讨论(0)
  • 2021-01-22 20:57

    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
    
    0 讨论(0)
  • 2021-01-22 20:59

    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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题