Transcations & Concurrency control (Theory and Practice) in T-SQL - Part 1

Table of Content

  1. Humble Intro to Transcations.

  2. Controlling Transactions

  3. Handling Erros in Transactions

Transactions in SQL Server

Transaction: atomic unit of work that might include multiple activities that query and modify data, A one or more statements, all or none of the statment are executed.

Imagine we have a bank account database, we need to transfer $100 from account A to account B the procedure as came to your mind is

  1. Subtract 100 from A

  2. Add those 100 to B so the operation here needs to be done as all statement , or not

Genreal Statement

BEGIN {TRAN | TRANSACTION }
   [ { transcation_name | @tran_name_variable}
      [ WITH MARK ['description'] ]
  ]
[;]

We can optionally add a transcation name and WITH MARK

 COMMIT [ {TRAN | TRANSACTION } [transcation_name | transc_name_variable ]]
[ WITH (DELAYED_DURABILITY = {OFF | ON } )][;]

once the commit is executed, the effect of transaction can't be reversed

ROLLBACK reverts the transaction to the beginning of it or a savepoint inside the transaction

we can define the boundaries (Beginning and end) of the transaction either:

  1. Explicitly The start of a transaction is defined by BEGIN and the end either to be COMMIT (in case you of success) or ROLLBACK if you need to undo changes

  1. Implicitly MS SQL Server automatically commits the transaction at the end of each individual statement, in case you didn't specify this explicitly we can change this behavior by changing the session option [IMPLICIT_TRANSACTION] to ON, by doing so, we don't need to specify the beginning of tran, but we need to specify the end of the train either committing it or rollbacking it.

Transaction properties

Transactions have four props: ACID

  • Atomicity

  • Consistency

  • Isolation

  • Durability

an example

the second example uses rollback, which will revert the operation to the original state

third example with try... catch we surrond transcation with try and catch

a fourth example of implicit transaction, which will cause only a three statement to be executed correctly.

resulting in an inconsistent state

Exercises

using @@ROWCOUNT to control when to rollback the transcation

@TRANCOUNT and savepoints

savepoints: @@TRANCOUNT returns the number of BEGIN TRAN statements that are active in your current connection Returns:

  • 0 -> no open transactions

  • greater than 0 -> open transaction

It's modified by:

  • BEGIN TRAN -> (which increases @@TRANCOUNT by 1) @@TRANCOUNT + 1

  • COMMIT TRAN -> @@TRANCOUNT - 1

  • ROLLBACK TRAN -> @@TRANCOUNT = 0 (except with savepoint_name)

an example of @@TRANCOUNT in nested transaction

@@TRASCOUNT value

0

@@TRANCOUNT in a TRY..CATCH construct

Savepoints are:

  • Markers within a transcations

  • Allow to rollback to the savepoints

let's see an example

only the last insert will took place

📓 note: savepoints don't affect the value of @@TRANSCOUNT

Examples

Controlling Errors of Transcations (XACT_ABORT & XACT_STATE)

XACT_ABORT specified whthere the currenct transction will be automatically rolled back when an error occrus

It can be set to on or off.

If an error occurs under the default setting which is by default OFF, the transcation can automatically be rolled back or not, depending on the error, if the transcations is not rolled back, it remains open

Setting it to ON, will ensure the transcation will be rolled bacek when an error occures and abort the transaction

Let's see an examples

The last statement generate an error of violating the uniqe key 'unique_email'

If we checked the customers table we'll see the first statement has been executed despite an error found on the transaction

customer_id
first_name
last_name
email
phone

14

yousef

meska

yousefmeska123.com

1545

Now If we turned XACT_ABORT to ON, the transaction will be rolled back an aborted

XACT_ABORT with RAISEERROR and THROW statement

XACT_STATE

It doesn't take any parameter. It returns

  • 0 -> no open transaction

  • 1 -> Open and committable transaction

  • -1 -> Open and uncommitable transactions (Doomed transaction)

When a transaction is Doomed that's means

  • You can't commit

  • You can't rollback ot a savepoint

  • You can only rollback the full transaction

  • You can't make any changes but you can read data

Let's see an examples In this example, the transcation will will commited if there's no error between TRY block, if there's an error, the catch will handle it by determing the state of the transcation And the state of the transaction will remains opem and commitable because we set XACT_ABORT to OFF if the transaction is commitable then the transcation will be commited if not it will be rolled backs

Only the first statement will be committed

customer_id
first_name
last_name
email

15

x

y

x@gmail.com

Let's see what happens when we need to make the transaction uncommitable?

The transaction has beed rolled back

Exercises

Last updated