如何保持特定记录的sql增量序列

时间:2015-07-30 02:07:31

标签: sql sql-server database-administration

我试图找出可以从一个点更新序列的SQL语句。你可以看到它停在15并从19开始,实际上19应该是16而20应该是17,依此类推。

SQL SERVER VERSION 11.0.5058

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在查询时轻松重新编号:

select t.*, row_number() over (order by col3)
from table t;

如果您想更新数字,可以执行以下操作:

with toupdate as (
      select t.*, row_number() over (order by col3) as newcol3
      from table t
     )
update toupdate
    set col3 = newcol3;

但是,如果列是表的id,则不要更改该值。不连续的ID很好,没有理由改变这些值。并且,如果值用于外键引用,则更改值可能会破坏数据库或花费很长时间。