I just noticed a Stored Procedure was using the following BEGIN/COMMIT TRAN.
BEGIN TRAN
INSERT INTO SomeTable
(
TypeID
)
VALUES
(
@TypeID
)
SET @OvID = SCOPE_IDENTITY()
COMMIT TRAN
Is it a good practice to use a Transaction on a INSERT and SCOPE_IDENTITY?
Will using a TRAN in this way slow down the INSERT process a lot?
I always think of using a Transaction when you have multiple statements that could fail (i.e. like two INSERTS). In this case, I can see the INSERT failing but I suspect the SCOPE_IDENTITY will always succeed.
For a single statement it doesn’t really matter, in that you aren’t gaining any additional atomicity or reliability. And
SCOPE_IDENTITY()can’t be affected by anything outside of your current batch, so wrapping it in aTRANSblock won’t have any affect.Whether it’s a good practice to get into is rather subjective so I’m intentionally not addressing it!