Transactions and Error Handling in SQL Server
Miriam Antona
Software Engineer
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
Dirty reads | Non-repeatable reads | Phantom reads | |
---|---|---|---|
READ UNCOMMITTED | yes | yes | yes |
READ COMMITTED | no | yes | yes |
Original balance account 5 = $35,000
Transaction1
BEGIN TRAN
UPDATE accounts
SET current_balance = 30000
WHERE account_id = 5;
Transaction2
...
...
...
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT current_balance
FROM accounts WHERE account_id = 5;
Has to wait!
Original balance account 5 = $35,000
Transaction1
BEGIN TRAN
UPDATE accounts
SET current_balance = 30000
WHERE account_id = 5;
COMMIT TRAN;
Transaction2
...
...
...
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT current_balance
FROM accounts WHERE account_id = 5;
| current_balance |
|-----------------|
| 30000,00 |
Transaction1
BEGIN TRAN
SELECT current_balance
FROM accounts WHERE account_id = 5;
Transaction2
...
...
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT current_balance
FROM accounts WHERE account_id = 5;
| current_balance |
|-----------------|
| 35000,00 |
Pros:
Cons:
When to use it?:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
Dirty reads | Non-repeatable reads | Phantom reads | |
---|---|---|---|
READ UNCOMMITTED | yes | yes | yes |
READ COMMITTED | no | yes | yes |
REPEATABLE READ | no | no | yes |
Transaction1
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
SELECT current_balance FROM accounts
WHERE account_id = 5;
| current_balance |
|-----------------|
| 35000,00 |
Transaction2
...
...
UPDATE accounts
SET current_balance = 30000
WHERE account_id = 5;
Has to wait!
Transaction1
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
SELECT current_balance FROM accounts
WHERE account_id = 5;
SELECT current_balance FROM accounts
WHERE account_id = 5;
| current_balance |
|-----------------|
| 35000,00 |
COMMIT TRAN
Transaction2
...
...
UPDATE accounts
SET current_balance = 30000
WHERE account_id = 5;
Has to wait!
Transaction1
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
SELECT current_balance FROM accounts
WHERE account_id = 5;
SELECT current_balance FROM accounts
WHERE account_id = 5;
COMMIT TRAN
Transaction2
...
...
UPDATE accounts
SET current_balance = 30000
WHERE account_id = 5;
(1 rows affected)
Pros:
Cons:
REPEATABLE READ
transaction.When to use it?:
Transactions and Error Handling in SQL Server