Click here to Skip to main content
16,015,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
When rollback the transaction , i want to keep committing the nested transaction and rollback only outer most transaction. How to do???

e.g.

TRY
Transaction A
Insert ....
Insert ....

Transaction B
Insert ....
Commit B

Insert ....
Commit
CATCH
Roll back A

here whenever exception is occurred then I want to rollback only A transaction not B.
Solution Appreciated
Posted

U can use Save Point functionality given for try can catch..

SQL
SET NOCOUNT ON
 
BEGIN TRAN
PRINT 'First Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)
 
INSERT INTO People VALUES ('Tom')
 
SAVE TRAN Savepoint1
PRINT 'Second Transaction: ' + CONVERT(VARCHAR,@@TRANCOUNT)
 
INSERT INTO People VALUES ('Dick')
 
ROLLBACK TRAN Savepoint1
PRINT 'Rollback: ' + CONVERT(VARCHAR,@@TRANCOUNT)
 
COMMIT TRAN
PRINT 'Complete: ' + CONVERT(VARCHAR,@@TRANCOUNT)
 
/* MESSAGES
 
First Transaction: 1
Second Transaction: 1
Rollback: 1
Complete: 0
 
*/
 
Share this answer
 
You may consider using a variable table on transaction B, rollback will not affect variable table, something like that :

declare @mytable table(....)
begin tran
insert A1...
insert @mytable...
rollback
select * from @mytable
 
Share this answer
 
Check with the below code may be this will help you

e.g.
Declare @A1Error int
Declare @A2Error int

Declare @B1Error int
Declare @B2Error int

Tran A
Insert A1
SET @A1Error = @@ERROR
Insert A2
SET @A2Error = @@ERROR

Tran B
Insert B1
SET @B1Error = @@ERROR
Insert B2
SET @B2Error = @@ERROR

--Commit or Rollback sql transaction B
IF @B1Error <> 0 OR @B2Error <>0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION

Commit or Rollback sql transaction A
IF @A1Error <> 0 OR @A2Error <>0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900