Wednesday, 26 July 2017

Transaction Commit and Rollback In SQL Server/ Why do i need Transactions In SQL Server

Introduction
In this article we will learn commit and rollback commands in sql server. What is transaction in sql. Why do we need commit and rollback in sql server. Can we rollback a table after performing operation on that table.

Previous Updates
In previous articles we have learnt What is Lock and how to achieve lock on sql table. How high quality content affects your WebsiteWhy every business needed digital Marketing and Why digital marketing Required. Authorization in Asp.Net. 

Database Structure
Before starting the Transaction commit and rollback , at first i am showing you my database structure. Insert and table creation script here.
CREATE TABLE TestEmpDetail ( ID INT Identity(1,1) Primary Key, Name Varchar(50), Address Varchar(250))

Insert Into TestEmpDetail Values( 'Jack', 'UK')
Insert Into TestEmpDetail Values( 'Mark', 'USA')
Insert Into TestEmpDetail Values( 'Rus', 'Eng')
Insert Into TestEmpDetail Values( 'Jow', 'UAE')
After inserting data Look at the table by using Select command.


















Commit In SQL
Commit is used for permanent changes in table. When commit perform in any query then the changes will not rollback.
Example  : 
BEGIN TRAN test
UPDATE TestEmpDetail set Name ='Bill' where ID=2
COMMIT TRAN test





Here test is the Transaction name and we update the TestEmpDetail table for Id 2. And these changes are committed so this change will not rollback.

Rollback In SQL
As its name suggest Rollback command is used for revert the changes done in table but before commit. The data which is committed or inserted into DB will not reverted or rollback.
SYNTAX
BEGIN TRAN tranName
--Command for operation
ROLLBACK TRAN tranName

BEGIN TRAN test
UPDATE TestEmpDetail set Name ='Bill1' where ID=2
UPDATE TestEmpDetail set Name ='Jaff' where ID=3

SELECT * FROM TestEmpDetail


Now you can see after the Test transaction table has two new updated entries . For id 2 and 3 named changes in SQL.
Now i will perform  rollback  statement on test named Transaction. After rollback the newly updated table data has lost. Because we only performed Begin Trans and no commit transaction done . 
ROLLBACK TRAN test;


No comments:

Post a Comment