这是此讨论的测试表
create table t4721736 ( id int identity primary key, name varchar(10), comm money )
insert t4721736 select 'John', 232.43 -- id=1
insert t4721736 select 'Alex', 353.52 -- id=2
-- check contents
select * from t4721736
-- do all this in a transaction
BEGIN TRAN
-- dummy insert
insert t4721736 select 'dummy', null
-- get what the id should be
declare @resetto bigint
set @resetto = scope_identity()
-- remove dummy record
delete t4721736 where id = @resetto
-- perform the insert(s)
set identity_insert t4721736 on;
insert t4721736(id,name,comm) select 10000000, 'Smith', 334.23;
set identity_insert t4721736 off;
-- reset the identity
set @resetto = @resetto - 1 -- it needs to be 1 prior
DBCC CHECKIDENT(t4721736, RESEED, @resetto)
COMMIT
假设您完全理解(我相信您理解),一旦范围达到具有指定 ID 的记录,它就会失败。SQL Server 不会对已附加记录的 ID 执行任何自动跳过。
这不是问题,因为当我使用 identity_insert 插入时,id 的值将大于 1000 万。所以不会有碰撞的问题
要查看这是如何失败的,请通过在上面的代码中将“10000000”更改为“10”来缩短该过程。然后,跟进这些:
-- inspect contents, shows records 1,2,10
select * from t4721736
-- next, insert 7 more records, bringing the id up to 9
insert t4721736 select 'U3', 0
insert t4721736 select 'U4', 0
insert t4721736 select 'U5', 0
insert t4721736 select 'U6', 0
insert t4721736 select 'U7', 0
insert t4721736 select 'U8', 0
insert t4721736 select 'U9', 0
最后,尝试下面的下一个插入
insert t4721736 select 'U10', 0