March 7, 2012 at 10:03 am
Hi,
I have the procedure shown below. As ou can see I am getting the identity of an auto increment field before the commit transaction. Is this a good practive or should I get the identity after commiting?
BEGIN TRY
BEGIN TRANSACTION
INSERT
INTO ST_Airports
(
[AirportCode],
[AirportName],
[CountryID]
)
VALUES
(
@sAirportCode,
@sAirportName,
@iCountryID
)
SET @iNewID = @@IDENTITY
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SET @iNewID = 0
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
EXEC spa_HandleError
END CATCH
March 7, 2012 at 10:55 am
From BOL @@IDENTITY
Is a system function that returns the last-inserted identity value.
Now is that what you want ... ?
I am thinking that you want the value AFTER the insert ....
March 8, 2012 at 12:46 am
It doesn't make any difference. The value will be available right after the INSERT takes place and you will discard it anyway if you can't reach the commit for any reason (you fall into the CATCH block).
-- Gianluca Sartori
March 8, 2012 at 6:39 am
Careful folks. @@IDENTITY won't work the way you think it will if a trigger is involved and you should always plan on someone adding such a thing in the future if it doesn't already exist. Use SCOPE_IDENTITY() instead.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 8, 2012 at 7:10 am
You're right Jeff (as usual)!
Thanks for pointing it out.
-- Gianluca Sartori
March 8, 2012 at 10:52 am
Yep, Jeff is correct. Scope_identity(), and understand that if the next identity value is 12, and the transaction fails, the next one inserted will be 13. The identity increments are not rolled back, which is what Gianluca mentioned.
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply