I have a stored procedure that has a BEGIN TRANSACTION
and COMMIT TRANSACTION
statement. Within the transaction is a select query WITH(XLOCK, ROWLOCK)
.
The transaction can potentially fail due to some calculations that cause an arithmetic overflow error if out of bounds values are supplied. This error would happen before any insert/update statements.
My question is, should I wrap the transaction in a TRY/CATCH and rollback or is this not really required and all locks would be released automatically if the transaction fails? My only concern here is that SQL would not release all locks of the transaction in case the transaction fails.
Thanks,
Tom
A much easier way is:
set xact_abort on
This will cause the transaction to be rolled back automatically when an error occurs.
Example code:
set xact_abort on
begin transaction
select 1/0
go
print @@trancount -- Prints 0
set xact_abort off
begin transaction
select 1/0
go
print @@trancount -- Prints 1
If you execute the second segment multiple times, you'll see the transaction count increase to 2,3,4 etc. A single run of the first segment resets all transactions.