public void TransferMoney( string toAccount
{
using ( SqlConnection conn = new SqlConnection(
{
SqlCommand cmdCredit = new SqlCommand(
cmdCredit
cmdCredit
cmdCredit
SqlCommand cmdDebit = new SqlCommand(
cmdDebit
cmdDebit
cmdDebit
conn
// Start a new transaction
using ( SqlTransaction trans = conn
{
// Associate the two command objects with the same transaction
cmdCredit
cmdDebit
try
{
cmdCredit
cmdDebit
// Both commands (credit and debit) were successful
trans
}
catch( Exception ex )
{
// transaction failed
trans
// log exception details
throw ex;
}
}
}
}
如何使用 Transact
以下存儲過程闡明了如何在 Transact
CREATE PROCEDURE MoneyTransfer
@FromAccount char(
@ToAccount char(
@Amount money
AS
BEGIN TRANSACTION
UPDATE Accounts
SET Balance = Balance
WHERE AccountNumber = @FromAccount
IF @@RowCount =
BEGIN
RAISERROR(
GOTO ABORT
END
DECLARE @Balance money
SELECT @Balance = Balance FROM ACCOUNTS
WHERE AccountNumber = @FromAccount
IF @BALANCE <
BEGIN
RAISERROR(
GOTO ABORT
END
UPDATE Accounts
SET Balance = Balance + @Amount
WHERE AccountNumber = @ToAccount
IF @@RowCount =
BEGIN
RAISERROR(
GOTO ABORT
END
COMMIT TRANSACTION
RETURN
ABORT:
ROLLBACK TRANSACTION
GO
[
From:http://tw.wingwit.com/Article/program/net/201311/15086.html