Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback an entire stored procedure

I have a stored procedure with multiple update statements.I dont want to use try catch.How can I rollback the stored procedure and get back the original table?

can something like this work -

begin transaction t1 spName rollback transaction t1

like image 908
Shivam Sharma Avatar asked Sep 10 '16 12:09

Shivam Sharma


People also ask

Can we use rollback in stored procedure?

Even in the case where an exception causes the stored procedure to abort, you must still use COMMIT or ROLLBACK after the procedure exits.

Can we rollback a transaction after it has committed?

COMMIT permanently saves the changes made by the current transaction. ROLLBACK undo the changes made by the current transaction. 2. The transaction can not undo changes after COMMIT execution.


1 Answers

Yes you can wrap everything into a sproc into a transaction

begin tran
exec testproc

commit tran
--rollback tran --for condition

It works fine even for commit as well rollback

If for inside the sproc you need to open another transaction then you need to capture

DECLARE @vTranCount   INT = @@TRANCOUNT

--Commit
IF (@vTranCount = 0 AND @@TRANCOUNT <> 0) COMMIT TRANSACTION --Commit if the Tran is created by this sproc

--rollback during catch
IF(@vTranCount = 0 AND @@TRANCOUNT > 0) ROLLBACK TRANSACTION --Rollback if the Tran is created by this sproc
like image 106
Kannan Kandasamy Avatar answered Sep 25 '22 07:09

Kannan Kandasamy