Skip to content

Instantly share code, notes, and snippets.

@demius
Created August 20, 2021 02:10
Show Gist options
  • Save demius/07427eca628da2604f6d4e8846877ad8 to your computer and use it in GitHub Desktop.
Save demius/07427eca628da2604f6d4e8846877ad8 to your computer and use it in GitHub Desktop.
SQL stored procedure template with transactions and exception handling
/*
A nice template for SQL TRY-CATCH with transactions
Taken from this SO discussion thread: https://stackoverflow.com/questions/7488149/sql-transaction-error-the-current-transaction-cannot-be-committed-and-cannot-su
*/
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(),
@message = ERROR_MESSAGE(),
@xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
end catch
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment