Ex:
Dim Conn As SqlConnection = UW.SQL.GetOpenedConnection
Dim Tran As SqlTransaction = Conn.BeginTransactionTry
Dim C As Int32 = UW.SQL.GetSingleValue("Select Counter From TableA Where Id = 1", Tran)
C = C + 1
UW.SQL.executeSQL("Update TableA Set Counter = " & C & " Where Id = 1", Tran)
Tran.Commit()
Catch ex As Exception
Tran.Rollback()
UW.WU.DebugWriteLine(ex.ToString, True, True)Finally
If Conn.State <> ConnectionState.Closed Then
Conn.Close()
End IfEnd Try
以上的程式由兩個 Session 同時執行時, 並不能保証 Counter 會被加 2
若是要保証兩個 Session 都會把 Counter 加一(總共加 2), 要把以下這一行
Dim C As Int32 = UW.SQL.GetSingleValue("Select Counter From TableA Where Id = 1", Tran)
改為
Dim C As Int32 = UW.SQL.GetSingleValue("Select Counter From TableA With(XLock) Where Id = 1", Tran)