7 Transactions
7 Transactions
successfully.
If any part of the transaction fails, it can be rolled back, meaning all changes
made
in the transaction are undone. This ensures data integrity and consistency.
Syntax:
BEGIN TRANSACTION;
-- operations go here
COMMIT; -- or ROLLBACK;
BEGIN TRANSACTION;
Explanation:
- BEGIN TRANSACTION;: Starts a transaction.
- UPDATE Accounts SET Balance = Balance - 200 WHERE AccountID = 1;: Deducts $200
from John Doe’s account.
- UPDATE Accounts SET Balance = Balance + 200 WHERE AccountID = 2;: Adds $200 to
Jane Smith’s account.
- COMMIT;: Finalizes the transaction, saving all changes.
BEGIN TRANSACTION;
BEGIN TRY
-- Deduct $200 from John Doe's account
UPDATE Accounts
SET Balance = Balance - 200
WHERE AccountID = 1;
-- Add $200 to Jane Smith's account (Let's say an error happens here)
UPDATE Accounts
SET Balance = Balance + 200
WHERE AccountID = 2;
Explanation:
- BEGIN TRY ... END TRY: Code within the TRY block attempts to run the transaction.
- BEGIN CATCH ... END CATCH: If any error occurs, the CATCH block rolls back the
transaction.
- ROLLBACK;: Undoes all changes made in the transaction if there is an error.
This ensures that if anything goes wrong, all changes are canceled, and the
database is left in a consistent state.
Note
1. Start a Transaction with BEGIN TRANSACTION.
2. Write Operations: Perform your updates, inserts, or deletes.
3. Commit or Rollback:
- Use COMMIT to save changes if everything succeeds.
- Use ROLLBACK to cancel changes if any part fails (usually with TRY and CATCH
blocks).