Transaction in SQL Server
Transaction in SQL Server
SQL server
Presented by: Grishma
Shrestha
Introduction
Definition:
• A transaction represents a logical unit of work in a database that contains
one or more operations executed together, ensuring that all operations
complete successfully or none at all.
Importance
This property ensures Transactions must This property Once a transaction has
that a transaction is an transition a database determines how been committed, its
all-or- nothing from one valid state to transaction integrity is effects are permanent,
operation; either all of another valid state, visible to other even in the event of a
its modifications are preserving the defined transactions, ensuring system failure, thus
performed, or none rules and constraints, that concurrent ensuring that
are, leaving the thus ensuring that no executions do not completed
system unchanged in invalid data is ever interfere with each transactions can be
the event of a failure. written during the other's operations, relied upon to persist.
process. providing a virtually
private workspace.
Types of Transaction
This statement marks The COMMIT Used to undo all Creates a point within a
the starting point of a statement indicates that operations performed transaction that allows
transaction, allowing all operations within within the transaction you to roll back to a
the database to track the transaction have since its initiation, specific location
changes made during been executed reverting the database without affecting the
the transaction's successfully, making all back to the state before entire transaction,
execution until it's changes permanent the transaction began, offering a more
either committed or within the database. particularly useful in granular
rolled back. error handling. recovery option.
Locking Mechanism
Purpose:
Locking is essential to prevent concurrent transactions
from conflicting, ensuring data integrity by controlling
access to resources during a transaction's execution
phase.
Types of Locking:
SQL Server employs different locks-including shared,
exclusive, and update locks-each serving specific
functions to balance concurrency and consistency.
BEGIN TRANSACTION;
UPDATE product
SET stock = stock - 1
WHERE product_id = 1 AND stock > 0;
IF @@ROWCOUNT = 0
BEGIN
ROLLBACK;
PRINT 'Transaction failed: Out of stock.';
RETURN;
END
-- Explicit transaction
BEGIN TRANSACTION;
UPDATE users
SET balance = balance - 1500
WHERE user_id = 1 AND balance >= 1500;
IF @@ROWCOUNT = 0
BEGIN
ROLLBACK;
PRINT 'Transaction failed: Insufficient balance.';
RETURN;
END
COMMIT;