Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 6

Advanced database

Transaction
• A transaction is a single unit of work that typically contains multiple T-SQL
statements.
• If a transaction is successful, the changes are committed to the database. However,
if a transaction has an error, the changes have to be rolled back.
• Each transaction must happen two things in SQL Server:
• Either all modification is successful when the transaction is committed.
• Or, all modifications are undone when the transaction is rollback.
Transaction properties

• Atomicity: This property ensures that all statements or operations included in the


transaction must be performed successfully.
• Otherwise, the whole transaction will be aborted, and all operations are rolled back into
their previous state when any operation is failed.
• Consistency: This property ensures that the database changes state only when a
transaction will be committed successfully.
• It is also responsible for protecting data from crashes.
• Isolation: This property guarantees that all transactions are isolated from other
transactions, meaning each operation in the transaction is operated independently. It
also ensures that statements are transparent to each other.
• Durability: This property guarantees that the result of committed transactions persists
in the database permanently even if the system crashes or failed.
• First, we need to begin the
transactions.
• Then we need to write the DML
operations which we want to execute
as a single unit.
• In the third step, we need to check for
errors.
• If there is any error i.e. any of the
DML statements fails, then roll
back the transaction (any data that
is modified in the database will be
rollback)
• else commit the transaction so that
the data is saved permanently to
the database.
• Syntax:
BEGIN TRANSACTION  
--- sql statement
-- Check for error  
IF(@@ERROR > 0) (if there is an error) 
BEGIN  
  ROLLBACK TRANSACTION  
END  
ELSE  
BEGIN  
   COMMIT TRANSACTION  
END  
•;

You might also like