Uploaded by Khiêm Trương Ngọc

04. Transactions

advertisement
Transactions
A transaction is a single unit of data operations that can be controlled so that either all the
modifications in a transaction occur, or none occur.
SQL Server has three ways of executing transactions: Implicit Transactions, Explicit
Transactions, and Auto-Commit Transactions.
Implicit and Auto-Commit Transactions are mutually exclusive.
Auto-Commit
By default SQL Server connections use Auto-Commit Transactions.
Any INSERT, UPDATE, or DELETE statement executed alone or in a batch will
automatically be applied to the database, example :
UPDATE CheckingAccount
SET Balance = Balance + 500
WHERE AccountID = ‘123456789-CK’
UPDATE SavingsAccount
SET Balance = Balance - 500
WHERE AccountID = ‘123456789-SV’
Implicit
The ANSI standard for the Structured Query Language specifies that no modifications should
be made to data unless explicitly committed.
SQL Server supports this specification through a connection property called
IMPLICIT_TRANSACTIONS.
When IMPLICIT_TRANSACTIONS is set to ON, any data modification will implicitly
begin a transaction, but will not close the transaction. The transaction will remain open until
it is explicitly committed or rolled back, example :
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRY
UPDATE CheckingAccount
SET Balance = Balance + 500
WHERE AccountID = ‘123456789-CK’
UPDATE SavingsAccount
SET Balance = Balance - 500
WHERE AccountID = ‘123456789-SV’
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
RAISERROR(’Account Transfer Failed’, 14,1)
END CATCH
Explicit
An explicit transaction requires a BEGIN TRANSACTION to begin the transaction and an
explicit
COMMIT TRANSACTION or ROLLBACK TRANSACTION to close the transaction,
example :
BEGIN TRY
BEGIN TRANSACTION
UPDATE CheckingAccount
SET Balance = Balance + 500
WHERE AccountID = ‘123456789-CK’
UPDATE SavingsAccount
SET Balance = Balance - 500
WHERE AccountID = ‘123456789-SV’
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
RAISERROR(’Account Transfer Failed’, 14,1)
END CATCH
Download