更改表以添加ID值为null的增量主键记录

时间:2019-05-16 09:43:30

标签: sql sql-server

我在sql server中有一个表,其中ID字段是主键。在ID字段的行中,有些具有主键值,而有些行则没有主键值,因为ID列允许为空。现在,我想运行一个查询以将值增量插入到为空的行中,以便它们可以具有主键值。我已经尝试过使用ALTER命令,但是没有前进的方向

2 个答案:

答案 0 :(得分:1)

因为您没有提供任何表结构描述,并且我们不知道是否存在任何业务键或存在某些独特的数据组合来标识没有主键的行,所以最简单的方法,恕我直言,是使用update光标:

begin tran
-- rollback
-- commit

select * from [Table_1] where id is null

declare @Id int, @i int = 0
    ,@MaxId int

set @MaxId = (select Max(Id) from [Table_1] )
declare Update_cur cursor local
    for select Id from [Table_1] where id is null
    for update of Id

open Update_cur
fetch next from Update_cur into @Id
while @@FETCH_STATUS = 0 begin
    set @i += 1
    update [Table_1] set Id = @MaxId + @i  where CURRENT OF Update_cur
    fetch next from Update_cur into @Id
end

close Update_cur
deallocate Update_cur

select * from [Table_1] order by Id

P.S。不要忘记在执行测试后提交或回滚事务

答案 1 :(得分:0)

您可以删除该列,然后使用“自动增量”值再次添加。

ALTER TABLE your_table DROP COLUMN ID
ALTER TABLE your_table ADD ID INT IDENTITY(1,1)

这将从一开始就生成所有值,结果您将丢失现有值(最多6个)。