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 |
原始餘額帳戶 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;
必須等待!
原始餘額帳戶 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 |
優點:
缺點:
何時使用?
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;
必須等待!
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;
必須等待!
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)
優點:
缺點:
REPEATABLE READ 交易阻擋何時使用?
SQL Server 的交易與錯誤處理