複習SQL

use northwind
go
 
update Products set UnitsInStock = 100 where ProductID = 1
update Products set UnitsInStock = 200 where ProductID = 2
update Products set UnitsInStock = 300 where ProductID = 3
go
 
select top 3 * from products
go
 
begin transaction
update Products set UnitsInStock = 111 where ProductID = 1
update Products set UnitsInStock = 333 where ProductID = 3
select top 3 * from products
select @@TRANCOUNT
rollback transaction
 
select @@TRANCOUNT
select top 3 * from products
go
 
-- All or Nothing
 
 
begin transaction
update Products set UnitsInStock = 111 where ProductID = 1
update Products set UnitsInStock = 333 where ProductID = 3
select top 3 * from products
select @@TRANCOUNT
commit transaction
 
select top 3 * from products
go

SqlCommand 的刪除法:

cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "delete from customers where customerId = '00001' ";
cmd.ExecuteNonQuery();

在 SQL 中,Dirty Read(髒讀) 是指在一個事務中讀取了另一個事務尚未提交的數據。這些數據可能最終被回滾(也就是撤銷),因此讀到的資料並不可靠,這就是為什麼被稱為「髒讀」。

Dirty Read 發生的情境:

  1. 事務 A 修改了一些資料,但還沒有提交(即這些變更對其他事務是不可見的)。
  2. 事務 B 讀取了這些未提交的變更(髒資料)。
  3. 如果 事務 A 最後回滾,那麼 事務 B 之前讀到的資料就成了無效的,因為那些變更已被撤銷。

這種情況通常會發生在 最低的隔離級別READ UNCOMMITTED。在這個隔離級別下,事務可以讀取其他事務尚未提交的變更,因此可能發生「髒讀」。

例子:

假設有一個銀行帳戶資料表,帳戶餘額目前是 100。

  1. 事務 A 開始,將餘額從 100 修改為 50,但還沒有提交。

    BEGIN TRANSACTION;
    UPDATE BankAccount SET Balance = 50 WHERE AccountID = 1;
    -- 尚未 COMMIT
    
    
  2. 事務 B 開始並讀取該帳戶的餘額,此時讀到的餘額是 50,儘管事務 A 尚未提交這個變更。

    SELECT Balance FROM BankAccount WHERE AccountID = 1;
    -- 事務 B 讀到的值是 50(髒讀)
    
    
  3. 事務 A 回滾操作,將帳戶餘額還原回 100。

    ROLLBACK;
    

此時,事務 B 讀到的餘額(50)是不正確的,因為實際上資料庫中的餘額還是 100。

避免 Dirty Read: