我有如下表:SQL服务器:重置身份如果出现错误
create table testTable
(
id int identity primary key,
string varchar(256),
constraint testConstraint unique(string)
)
具有以下触发:
create trigger testTrigger
on testTable
for delete as
begin
declare @max_ int
select @max_= max(id) from testTable
if @max_ is null
set @max_ = 0
DBCC CHECKIDENT ('testTable', RESEED, @max_)
end
执行以下命令:
insert into testTable(string) values ('test') --identity = 1
insert into testTable(string) values ('test') --error thrown because duplicate key but **identity = 2**
insert into testTable(string) values ('test1') --due to erroneous identity increment identity = 3
第一插入设置标识= 1,第二个由于唯一(字符串)约束而抛出错误,但是i牙齿错误设置为2。
问题是我该如何使错误不会增加身份?
是否有做,所有待所有SQL Server当该鉴别是基于什么已经列/表以确保生产顺序方式的功能?这样所有的边缘情况都会被捕获。
在此先感谢(:
我认为你非常重视拥有完美的数据。身份差距是完全正常和预期的。它在每次插入尝试时递增,即通过设计。当一行被删除时,间隙也会出现。如果您使用的是2012+,则可以使用序列,但在删除某行时仍会有空白。 –
感谢@SeanLange,你能提供一个关于如何创建这个序列的指导方针吗?我对此没有任何认识。 –
https://www.google.com/search?q=sql+server+sequence&ie=utf-8&oe=utf-8 –