Cannot roll back SaveTran. No transaction or savepoint of that name was found.
Nested Transactions
CREATE TABLE NestedTransaction ( Id INT)GOBEGIN TRAN OuterTxnINSERT INTO NestedTransaction VALUES(1)BEGIN TRAN InnerTxnINSERT INTO NestedTransaction VALUES(1)ROLLBACK TRAN InnerTxnSELECT @@TRANCOUNT
Above script will throw an error while trying to rollback the inner transaction and the transaction count is two which means that there are two open transactions in the current session. Try to execute the below two lines
ROLLBACK TRAN OuterTxnGOSELECT @@TRANCOUNT
BEGIN TRAN OuterTxnINSERT INTO NestedTransaction VALUES(1)BEGIN TRAN InnerTxnSELECT @@TRANCOUNT
INSERT INTO NestedTransaction VALUES(2)COMMIT TRAN InnerTxnSELECT @@TRANCOUNTROLLBACK
CREATE TABLE NestedTransaction_1 ( Id INT)GOCREATE TABLE NestedTransaction_2 ( Id INT)CREATE TABLE NestedTransaction_3 ( Id INT)GOBEGIN TRAN OuterTxnINSERT INTO NestedTransaction_1 VALUES(1)BEGIN TRAN InnerTxn_1INSERT INTO NestedTransaction_2 VALUES(1)BEGIN TRAN InnerTxn_2INSERT INTO NestedTransaction_3 VALUES(1)
Logically the locks on each table should be held by respective transactions but if you look into the TransactionName column in the output of this query (Query to find the locking info), it will be outer transaction. Partial Rollback of Transactions
Partial rollback of transaction is possible by setting a save point inside a transaction using the Save Transaction command. Please find the sample script below.
CREATE TABLE PartialTxn( Name CHAR(10))
GO--Transaction Starting hereBEGIN TRAN
INSERT INTO PartialTxn VALUES('James')--Setting the savepointSAVE TRANSACTION Txn1INSERT INTO PartialTxn VALUES('George')SELECT * FROM PartialTxn ROLLBACK TRANSACTION Txn1COMMIT
SELECT * FROM PartialTxn
You can see that only one record exists in the table after the final commit. This can be implemented inside the procedure also. In case of multiple procedures are part of single transaction , you can rollback only the failed(due to some validation error) procedure and can still commit the remaining data.
If you liked this post, do like my page on FaceBook at http://www.facebook.com/practicalSqlDba