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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Shankar MPosted Dec 1, 2012, 6:21 AM
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.
Pradip PandeyPosted Nov 28, 2012, 12:42 AM
Please refer this link.
http://www.c-sharpcorner.com/Blogs/5318/
Hope it will help.