我有如下表: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 –