Link to home
Start Free TrialLog in
Avatar of Ali Saad
Ali SaadFlag for Kuwait

asked on

Identity Column in SQL Server

Hello
I have a  table with an Identity Column
Create  Table T1(  Col1 INT Identity Primary Key ,COL2nvarchar(100) ...........)
When the insert statement failed for  any reason the Col1 still increasing .....
1-  Can i change this behaviour ? I means is there a documented way to prevent the Auto increment IF the insert operation failed ?
2- When i use Scope_IDENTITY() function it Returns  the SUCCSSED inserted Identity .. what about if INSERT failed how can i get the autoIncremental number for the failed insert?
Avatar of Pavel Celba
Pavel Celba
Flag of Czechia image

1) You may execute the INSERT statement in a transaction and the identity value should not change.

2) You may select MAX value from the table.
Sorry, I have to correct myself. Transaction does not affect Identity value and you cannot use it to keep the identity column values consecutive.

So, the only way it to use your own procedure which will generate "identity" values based on some table containing counters. You'll also need a mechanism to reuse the generated counter value when the insert command fails.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial