Wednesday, August 7, 2013

Transactions in SQL Server



Transactions

A transaction groups a set of task into a single execution unit. Every transaction begins with a specific task and ends when all the tasks in the group successfully complete. If the execution of any of the tasks is fails, the transaction is fails. Therefore, we can say a transaction has only two results: success or failure. Any incomplete steps result in the failure of the total transaction.


Properties of Transactions

Every Transaction has the following four standard properties and in short form generally called ACID:
  1. Atomicity: Ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is will be failed and previous operations are rolled back to their previous state.
  2. Consistency: Ensures that the database properly changes its state based on a successfully committed transaction.
  3. Isolation: Enables transactions to work independently.
  4. Durability: Ensures that the effect of a committed transaction persist in case of any failure.


Transaction Control

The following commands are used to control transactions:
  • Begin Transaction
  • Rollback Transaction
  • Commit Transaction


Example
      BEGIN TRAN
      BEGIN TRY
            --INSERT INTO SQL statement
            --INSERT INTO SQL statement
            COMMIT TRAN
      END TRY    
      BEGIN CATCH
            ROLLBACK TRAN --For Error
            SELECT ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;
      END CATCH

0 comments:

Post a Comment