Rollback in Stored Procedure
How to Rollback a transaction in Stored Procedure?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pradip PandeyRank #452 · 5.6K reputationPosted Nov 27, 2012, 7:42 PM EST
Please refer this link.
http://www.c-sharpcorner.com/Blogs/5318/
Hope it will help.
Shankar MRank #874 · 2.5K reputationPosted Dec 1, 2012, 1:21 AM EST
Hi Swathi,
The Stored Procedure should have a BEGIN TRANSACTION, from where the transaction starts. You can check for @@ERROR or TRY..CATCH for Exception handler to handle the errors. If an error is occured, the Transaction can be rolled back using ROLLBACK statment.
If you have two insert statements, if you are to use @@ERROR variable to check the error then, @@ERROR has to be checked twice for each Insert statments like,
INSERT INTO EMP(EMPNO,DEPT) VALUES(1234,20);
IF @@error <>0
BEGIN
ROLLBACK
RAISERROR ('Error Inserting 1', 16, 1)
RETURN
END
INSERT INTO DEPT(DEPTNO)VALUES(20);
IF @@error <>0
BEGIN
ROLLBACK
RAISERROR ('Error Inserting 2', 16, 1)
RETURN
END
So, the @ERROR is variable is not reset for either the statement goes in to error.. So as to preserve the Atomicity of a Transaction.
To avoid this writing lengthy code of checking @@ERROR variable for each statement,
you can use TRY..CATCH block.