This article explains how to use the transactions and various way of writing the transactions in SQL Server. Please see the examples to understand better. I have taken an example to explain this in details.First you need to create two tables. The tables are as follows.Employee TableDepartment TableEXAMPLE 1: SIMPLE TRANSACTIONIn the following example, I am inserting the data to the employee table. I am using TRAN1 as my transaction. I am committing the transition in a try block and rolling back the same transaction in a catch block. Here there is no error so the transaction is committed.RUNEXAMPLE 2: ROLL BACK TRANSACTIONHere I am using an error statement after an insert statement, so the commit transaction will not be executed and it will go to the catch block. In the catch block, the rollback statement will be executed and the entire transaction will be rolled back.RUNEXAMPLE 3: ROLL BACK TRANSACTIONHere I am using an error statement after the commit transaction. The records will be inserted but the Stored Procedure will give you an error. Once you commit the transaction, you cannot roll it back.RUNEXAMPLE 4: SIMPLE NESTED TRANSACTIONSRUNEXAMPLE 5: NESTED TRANSACTIONSRUNEXAMPLE 6: NESTED TRANSACTIONSRUNEXAMPLE 7: TWO SEPARATE TRANSACTIONRUNEXAMPLE 8: TRANSACTION WITHIN A STORED PROCEDURESTORED PROCEDURE 1STORED PROCEDURE 2RUNEXAMPLE 9: TRANSACTION WITHIN A STORED PROCEDURESTORED PROCEDURE 1STORED PROCEDURE 2RUNNOTEHope you will enjoy this article. Please provide the feedback.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: