Sql 使用递增值更新表中的int列

Sql 使用递增值更新表中的int列,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,嗨,我如何用以某个值开始的增量值更新列 例如,如果使用下面的示例数据存储表 ProID ProName 1 Pro1 2 Pro2 3 Pro3 etc .. 如何使用起始值更新ProID值,例如10,然后增加其余值,使其 ProID ProName 10 Pro1 11 Pro2 12 Pro3 etc .. 我将为这个问题提供一个更一般的答案。我假设ProId有一个唯一的索引。因此,显而易见的解决方案是: update store

嗨,我如何用以某个值开始的增量值更新列

例如,如果使用下面的示例数据存储表

ProID ProName
1     Pro1
2     Pro2
3     Pro3
etc ..
如何使用起始值更新
ProID
值,例如10,然后增加其余值,使其

ProID ProName
10     Pro1
11     Pro2
12     Pro3
etc ..

我将为这个问题提供一个更一般的答案。我假设
ProId
有一个
唯一的
索引。因此,显而易见的解决方案是:

update store
    set ProID = ProID + 9;
不保证能工作。它可能会生成重复项(如果已经有id=10)。它无法填补空白

不幸的是,我认为您需要分两步完成这项工作(当存在唯一索引时)。更新表时出现重复问题。如果这样做有效,那么很好:

with toupdate as (
      select s.*, 9 + row_number() over (order by ProId) as new_ProId
      from store
     )
update toupdate
    set ProId = new_ProId;
但是,您可能需要执行以下操作:

with toupdate as (
      select s.*, 9 + row_number() over (order by ProId) as new_ProId
      from store
     )
update toupdate
    set ProId = - new_ProId;  -- ensure no duplicates by using a negative sign

update store
    set ProId = - ProId;      -- get rid of the negative sign

尽管如此,更新表的主键几乎从来都不是正确的做法。值中的差距通常不是问题。如果出于某种原因需要,您可以在查询表时使用
行编号()
来消除间隙。

更新存储集ProID=ProID+9
。如果这不起作用,请用更好的例子更新你的问题(在有人提供答案之前,这样的更新会使他们的答案无效)。
with toupdate as (
      select s.*, 9 + row_number() over (order by ProId) as new_ProId
      from store
     )
update toupdate
    set ProId = - new_ProId;  -- ensure no duplicates by using a negative sign

update store
    set ProId = - ProId;      -- get rid of the negative sign