Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

Nested Transaction in SQL Server

$
0
0
Transaction: Transaction is the collection of T-SQL statements which executes in single unit. Transaction begins with a specific T-SQL statement and ends when all T-SQL statements execute successfully. If any statements fail then transaction fails. Transaction has only two types of results success or failed. For more detail, what is Transaction inSQL Server?

Nested Transaction:  Microsoft SQL Server allows starting transaction within transaction which is called Nested Transaction. Nested transaction can be COMMIT but can’t be ROLLBACK.

See Following Example:


CREATETABLEEmployee
(
            IDINTPRIMARYKEY,
            NameVARCHAR(50),
            Emp_AddressVARCHAR(100)
)


Run above script to create an Employee table where ID column is PRIMARY KEY. Now see following script.

BEGIN
            BEGINTRY
                        BEGINTRANSACTIONOUT1
                                    INSERTINTOEmployeeVALUES(1,'DILIP','NOIDA')                  
                                    BEGINTRANSACTIONINNER1
                                    INSERTINTOEmployeeVALUES(1,'RAJ','DELHI')                     
                        COMMITTRANSACTION            
            ENDTRY
            BEGINCATCH
                  ROLLBACKTRANSACTIONINNER1
            ENDCATCH
END


This script will generate an error “Cannot roll back INNER1. No transaction or savepoint of that name was found.

Employee has “ID” PRIMARY KEY column in both transactions we trying to insert same value 1 so our transaction failed. In CATCH block we trying to ROLLBACK to INNER1 transaction so above we got an error.
If we are trying to rollback to OUT1 transaction it will run without error.
See following script


BEGIN
            BEGINTRY
                        BEGINTRANSACTIONOUT1
                                    INSERTINTOEmployeeVALUES(1,'DILIP','NOIDA')                  
                                    BEGINTRANSACTIONINNER1
                                    INSERTINTOEmployeeVALUES(1,'RAJ','DELHI')                     
                        COMMITTRANSACTION            
            ENDTRY
            BEGINCATCH
            ROLLBACKTRANSACTIONOUT1
            ENDCATCH
END


Note: Here SQL server allow to rollback only outer transaction and rollback of outer transaction will rollback all inner transaction.
Using Save transaction we can perform partial rollback in transaction

Using SAVE TRANSACTION command we can perform partial rollback, see following script


BEGINTRANSACTION
INSERTINTOEmployeeVALUES(1,'DILIP','NOIDA')      
--Save transaction Command
SAVETRANSACTIONINNER1
INSERTINTOEmployeeVALUES(2,'RAJ','DELHI')         
SELECT*FROMEmployee
ROLLBACKTRANSACTIONINNER1
COMMIT
SELECT*FROMEmployee



Here will find only one record in table after final commit.

Viewing all articles
Browse latest Browse all 265