Friday, 28 August 2015

Commit And Rollback Command

Commit Command:

Commit is used for the permanent changes. When we use Commit in any query then the change made by that query will be permanent and visible. We can't Rollback after the Commit.
Syntax:

begin tran tranName
Command for operation
commit tran tranName
Here tranName is the name of the transaction and the command for operation is the SQL statement that is used for the operation like making a change or inserting data etc.
Example:

begin
 tran d
update
 emp set empName ='D' where empid=11
commit
 tran d
Rollback Command:
Rollback is used to undo the changes made by any command but only before a commit is done. We can't Rollback data which has been committed in the database with the help of the commit keyword.

Syntax:
begin tran tranName
Command for operation
Rollback tran tranName
Here tranName is the name of the transaction and the command for the operation is the SQL statement that is used for performing operations like to make any change or insert data etc.

Example:
We want that, if data entered by user has an empId less than 10 then the command is rolled back and a message isshown to the user "An id less than 10 is not valid; query is rolled back".
 

begin tran t
declare
 @id int;
set
 @id=1;
insert
 into emp values(@id,'d')
if
(@id<10)
begin
print
'An id less than 10 is not valid; query is rolled back';
rollback
 tran t;
end 
else
begin
print
 'data is inserted'
end

No comments:

Post a Comment