在SQL Server中,当表中有一个Identity列,当你在这个表中插入一条记录时,如果插入失败,例如由于检查约束,identity仍然会增加。
如果你想防止这种情况发生。您可以尝试创建一个“代替”触发器。例如:
CREATE TABLE TestTable
(
ID int IDENTITY (1, 1) NOT NULL,
Name varchar(30) NOT NULL ,
)
INSERT INTO TestTableVALUES ('Bob')
-- This will fail since NULL is not allowed
-- But id still +1
INSERT INTO TestTable VALUES (NULL)
INSERT INTO TestTable VALUES ('Mike')
-- Create INSTEAD OF trigger
CREATE TRIGGER TestTrigger
ON TestTable
INSTEAD OF INSERT
AS
-- Get the value(s) being inserted
-- and repeat the insert
Declare @value varchar(100)
SET @value = (SELECT Name FROM Inserted)
-- If this statement fails, SQL won't increase the IDENTITY
INSERT INTO TestTable VALUES (@value)
-- Run the same INSERT again, when failed, ID will not increase
INSERT INTO TestTable VALUES('test1')
INSERT INTO TestTable VALUES(NULL)
INSERT INTO TestTable VALUES('test2')
SELECT * FROM TestTable