Reputation: 163
I have the following table:
create table testTable
(
id int identity primary key,
string varchar(256),
constraint testConstraint unique(string)
)
with the following trigger:
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
Executing the following commands:
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
The first insertion sets identity = 1, the second throws an error because of unique(string) constraint but identity is erroneous set to 2.
The question is how do I make it so that errors do not increment identity?
Is there a do-all be-all feature of SQL Server where the identity is ensured to be produced in a sequential fashion based on what's already in the column/table? Thus all edge cases such as this will be captured.
Thanks in advance (:
Upvotes: 1
Views: 69
Reputation: 5846
As others have mentioned, don't worry about gaps in the identity column coming from DELETE
s.
If you absolutely need an increment number with no gaps in it, you could handle that on the SELECT side when needed.
For example, see ROW_NUMBER ... this can be used along with sorting on a timestamp column of your linking (something like SYSUTCDATETIME) to get the exact sequence of addition for rows, ORDER DESC
, with ROW_NUMBER()
in the query.
This will NOT be tied to the data, because if rows are DELETE
d, these ROW_NUMBERS will change.
Upvotes: 1
Reputation: 2651
There shouldn't be any need to prevent gaps in an identity column. It sounds like you might be applying business logic to a surrogate key, which kind of defeats the purpose. You could do a sequence as Sean Lange points out in the comments.
Upvotes: 0