Rollback of nested transaction throwing error in TSQL - sql

Here is a snippet of what I am trying to achieve. I have a nested transaction 'tran2', which I can't rollback
SELECT 'Before', * FROM [table] WHERE field ..
BEGIN TRAN tran1
UPDATE [table] set field ... WHERE field ..
BEGIN TRAN tran2
SELECT 'During', * FROM [table] WHERE field ..
select ##trancount as 'transactioncount'
rollback tran tran2
rollback TRAN tran1
SELECT 'After', * FROM [table] WHERE field ..
is throwing me this error
Msg 6401, Level 16, State 1, Line 13
Cannot roll back tran2. No transaction or savepoint of that name was found.
however the ##trancount is giving me 2 transactions at that point

Instead of begin trans tran2, use save transaction tran2.
This creates a save point within the outer transaction, which you can rollback to.

Related

The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION, but still getting an error

Simple query:
Before the UPDATE, the value of EffectiveStartDt is NULL
After the UPDATE and the ROLLBACK, I want it to go back to NULL
begin tran t1
update MasterPayor
set EffectiveStartDt = '2020-09-17'
where MasterPayorId = 1
commit
rollback tran t1
I have defined the transactions, but I'm still getting the Rollback error
The COMMIT commits the update to the Database and clears the transaction begun with the matching BEGIN TRAN, hence the error when you try to rollback. If you want to ROLLBACK use the ROLLBACK without the COMMIT:
begin tran t1
update MasterPayor
set EffectiveStartDt = '2020-09-17'
where MasterPayorId = 1
rollback tran t1

How to handle Transaction in Nested procedure in SQL server?

I have 2 proc i.e. Proc1 and Proc2.
I am executing proc1 inside proc2. There are multiple DML operation in both procedure. output of proc1 is used in proc2 for DML operation.
if Error occurred in proc2 then
how to handle transaction in both proc for rollback all DML operation?
Should I write transaction in both proc?
We use a generic error handler procedure based on http://www.sommarskog.se/error_handling/Part1.html that we - when applicable - include in our (nested) transactions to ensure the chain is managed properly:
CREATE PROCEDURE [dbo].[sp_ErrorHandler](#caller VARCHAR(255))
AS BEGIN
SET NOCOUNT ON;
DECLARE #errmsg NVARCHAR(2048), #severity TINYINT, #state TINYINT, #errno INT, #lineno INT;
SELECT #errmsg=REPLACE(ERROR_MESSAGE(), 'DatabaseException: ', 'DatabaseException: '+QUOTENAME(#caller)+' --> ')
, #severity=ERROR_SEVERITY()
, #state=ERROR_STATE()
, #errno=ERROR_NUMBER()
, #lineno=ERROR_LINE();
IF #errmsg NOT LIKE 'DatabaseException%' BEGIN
SELECT #errmsg=N'DatabaseException: '+QUOTENAME(#caller)+N', Line '+LTRIM(STR(#lineno))+N', Error '+LTRIM(STR(#errno))+N': '+#errmsg;
END;
RAISERROR('%s', #severity, #state, #errmsg);
END;
(Compiled in the master database and marked as system procedure)
We use this error handler as follows. In the demo I have an outer proc and an inner proc both using a transaction.
CREATE PROCEDURE dbo.uspOuterProc
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
EXEC dbo.uspInnerProc;
PRINT 1;
COMMIT;
END TRY
BEGIN CATCH
IF ##trancount > 0
ROLLBACK TRANSACTION;
EXEC master.dbo.sp_ErrorHandler #caller = 'dbo.uspOuterProc';
END CATCH;
END;
GO
CREATE PROCEDURE dbo.uspInnerProc
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
PRINT 2;
SELECT 1 / 0;
PRINT 3;
COMMIT;
END TRY
BEGIN CATCH
IF ##trancount > 0
ROLLBACK TRANSACTION;
EXEC master.dbo.sp_ErrorHandler #caller = 'dbo.uspInnerProc';
END CATCH;
END;
GO
After you compile this and run:
EXEC dbo.uspOuterProc
You should get this result:
2
Msg 50000, Level 16, State 1, Procedure sp_ErrorHandler, Line 13 [Batch Start Line 48]
DatabaseException: [dbo.uspOuterProc] --> [dbo.uspInnerProc], Line 12, Error 8134: Divide by zero error encountered.
You can handle the transaction in the outer procedure ( in your case proc2). If any error will be occurred in proc1 it will be taken care of by proc2 transaction handler.
Am assuming that proc1 will not be called directly, it will be called inside the proc2.
There are 3 basic transaction handling statements (and a few advanced ones I'm not gonna mention):
BEGIN TRANSACTION: Will raise the ##TRANCOUNT session variable by 1. If it goes from 0 to 1 then this marks the start of a transaction. Any value higher than 1 will keep the same transaction ongoing.
COMMIT: Will lower the ##TRANCOUNT session variable by 1. If it goes from 1 to 0 then the transaction is marked as finished and will impact all changes done since it was first created.
ROLLBACK: Will decrease the ##TRANCOUNT session variable to 0 (whichever it's value was), as long as it was at least 1 or higher. This will close the transaction and revert all changes done since it was first created.
Nested transactions are a bunch of BEGIN TRANSACTION statements put together. The only point where the transaction gets fully commited and the changes are made permanent is when there is a COMMIT that lowers the transaction count from 1 to 0. That means you need one COMMIT for each BEGIN TRANSACTION you executed, like a pyramid.
Check the following example:
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 1
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 2
COMMIT TRANSACTION
SELECT ##TRANCOUNT -- 1 (no change is permanent yet, not even the last one)
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 2
ROLLBACK
SELECT ##TRANCOUNT -- 0 (all changes were discarded)
When you have an SP that executes another SP and both have their transactions, the only thing you need to care about is to CATCH errors and do the proper ROLLBACK IF there's an open/active transaction ongoing (if not the ROLLBACK statement will fail saying that there is nothing to rollback).
A very basic CATCH would be like the following:
BEGIN TRY
BEGIN TRANSACTION
/* Do some operations */
/* Execute another SP that might have the following:
BEGIN TRANSACTION
-- Some other operations
COMMIT
*/
COMMIT
END TRY
BEGIN CATCH
DECLARE #v_ErrorMessage VARCHAR(MAX) = ERROR_MESSAGE()
IF ##TRANCOUNT > 0 -- Only rollback if there is an active transaction
ROLLBACK
RAISERROR (#v_ErrorMessage, 16, 1)
END CATCH
You can read this post if you want to delve deeply into the best way for handling transactions on SQL Server.

The current transaction cannot be committed and cannot be rolled back to a savepoint. Roll back the entire transaction - 'Msg 3931, Level 16, State 1

I use SQL Server 2014 and I have run this test T/SQL.
BEGIN TRY
BEGIN TRANSACTION T1
CREATE TABLE aa9
(
A int
)
SAVE TRANSACTION S1
INSERT INTO aa9 (A) VALUES ('aa')
COMMIT TRANSACTION T1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION S1
PRINT 'Error ..... '
;throw
END CATCH
Why do I get this error:
Msg 3931, Level 16, State 1, Line 17
The current transaction cannot be committed and cannot be rolled back to a savepoint. Roll back the entire transaction.
Should I be able to Rollback the transaction to my SavePoint transaction?
You can really only rollback Save Transactions if your XACT_State() isn't -1.
This doesn't really apply to Insert Statements as that will blow the XACT_State() of all the transactions even if you rollback the save point.
So you can use it for stuff like Dividing By Zero and Conversion Errors but SQL Server isn't as sophisticated as you would hope.
However you can get some form of nested transactions as provided you add a bunch of checking as shown below.
Obligatory link to MSDN:https://learn.microsoft.com/en-us/sql/t-sql/functions/xact-state-transact-sql?view=sql-server-ver16
DROP TABLE IF EXISTS aa9;
BEGIN TRANSACTION T2;
BEGIN TRY
CREATE TABLE aa9
(
A int
)
PRINT 'Starting T2'
SAVE TRANSACTION T2;
INSERT INTO aa9(A) VAlUES (1);
PRINT 'Starting T3'
BEGIN TRANSACTION T3
SAVE TRANSACTION T3
BEGIN TRY
INSERT INTO aa9 (A) VALUES (2)
PRINT 'Forcing Error that doesn''t blow XACT_STATE()'
SELECT 1/0 --Comment This Line To See Difference
INSERT INTO aa9(A) VALUES ('A')
PRINT 'Committing T3'
COMMIT TRANSACTION T3
END TRY
BEGIN CATCH
PRINT 'Rolling Back T3'
ROLLBACK TRANSACTION T3;
THROW
END CATCH
COMMIT TRANSACTION T2;
END TRY
BEGIN CATCH
IF XACT_STATE() = -1
BEGIN
ROLLBACK TRANSACTION
PRINT 'Error ..... '
END
ELSE
BEGIN
COMMIT TRANSACTION T2;
PRINT 'Preserving T2..... '
END;
throw
END CATCH
GO
SELECT * FROM aa9

Can I open 2 transactions with different names

Can I have 2 transactions in a stored procedure like below? If I rollback TRAN1, does it rollback all TRAN2? I am lost here, any feedback will help. Thanks in advance
BEGIN TRANSACTION TRAN1
WHILE(...)
BEGIN
BEGIN TRANSACTION TRAN2
BEGIN TRY
.....
.....
.....
COMMIT TRANSACTION TRAN2
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION TRAN2
END CATCH
END
COMMIT TRANSACTION TRAN1
No matter ,how many transactions you have ,Outer rollback rollbacks all the transactions..
When you nest transactions like in your case,each committ/rollback increases or decreases ##trancount..
From MSDN..
Each BEGIN TRANSACTION statement increments ##TRANCOUNT by one. Each COMMIT TRANSACTION or COMMIT WORK statement decrements ##TRANCOUNT by one.
ROLLBACK TRANSACTION that uses the transaction name of the outermost transaction in a set of nested transactions rolls back all of the nested transactions and decrements ##TRANCOUNT to 0
See this as well :A SQL Server DBA myth a day: (26/30) nested transactions are real
Below is demo to test this behaviour..
if object_id('t1','u') is not null
drop table t1
create table t1
(
id int
)
go
begin tran outertran
select ##trancount--1
insert into t1
select 1
begin tran innertran
select ##trancount--2
insert into t1
select 2
/**below throws error,since you can reference only outer transaction
-referrring inner tran is not legal
***/
--rollback tran innertran
/***
error you get by uncommneting above
Msg 6401, Level 16, State 1, Line 20
Cannot roll back innertran. No transaction or savepoint of that name was found.
**/
commit tran innertran
select ##trancount--1
rollback --rollbacks all
select * from t1
References :
http://www.sqlskills.com/blogs/paul/a-sql-server-dba-myth-a-day-2630-nested-transactions-are-real/

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
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