Lab 2
Lab 2
Page 1 of 7
Example 2: Conditionally Rolling Back a Transaction with Error Message
BEGIN TRANSACTION;
BEGIN TRY
-- Perform some operations
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2;
-- Commit the transaction if no errors
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Rollback the transaction in case of error
ROLLBACK TRANSACTION;
PRINT 'Error occurred, transaction rolled back';
END CATCH;
Page 2 of 7
Example 2: Nested TRY...CATCH for Detailed Error Handling
BEGIN TRANSACTION;
BEGIN TRY
BEGIN TRY
-- Perform some operations
INSERT INTO Orders (CustomerID, OrderDate) VALUES (1,
GETDATE());
END TRY
BEGIN CATCH
-- Handle errors for Orders table
PRINT 'Error occurred in Orders table: ' + ERROR_MESSAGE();
THROW;
END CATCH;
BEGIN TRY
-- Perform some operations
INSERT INTO OrderDetails (OrderID, ProductID, Quantity) VALUES
(SCOPE_IDENTITY(), 1, 10);
END TRY
BEGIN CATCH
-- Handle errors for OrderDetails table
PRINT 'Error occurred in OrderDetails table: ' +
ERROR_MESSAGE();
THROW;
END CATCH;
Page 3 of 7
END CATCH;
Page 4 of 7
END CATCH;
Nested Transactions
Objective: Learn to manage nested transactions and ensure proper rollback
or commit in nested scenarios.
Example 1: Simple Nested Transactions
BEGIN TRANSACTION;
BEGIN TRY
-- Outer transaction
UPDATE Customers SET Status = 'Active' WHERE CustomerID = 1;
BEGIN TRANSACTION;
-- Inner transaction
BEGIN TRY
INSERT INTO Orders (CustomerID, OrderDate) VALUES (1,
GETDATE());
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Rollback inner transaction
ROLLBACK TRANSACTION;
PRINT 'Inner transaction rolled back';
THROW;
END CATCH;
-- Commit outer transaction
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Rollback outer transaction
ROLLBACK TRANSACTION;
PRINT 'Outer transaction rolled back: ' + ERROR_MESSAGE();
END CATCH;
Page 5 of 7
Page 6 of 7
Example 2: Nested Transactions with Save points
BEGIN TRANSACTION;
BEGIN TRY
-- Outer transaction
UPDATE Products SET Quantity = Quantity - 10 WHERE ProductID = 1;
-- Savepoint
SAVE TRANSACTION SavePoint1;
BEGIN TRY
-- Inner transaction
INSERT INTO Inventory (ProductID, Quantity) VALUES (1, 50);
-- Commit only if no errors
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Rollback to savepoint on error
ROLLBACK TRANSACTION SavePoint1;
PRINT 'Inner transaction rolled back to SavePoint1';
THROW;
END CATCH;
END TRY
BEGIN CATCH
-- Rollback outer transaction
ROLLBACK TRANSACTION;
PRINT 'Outer transaction rolled back: ' +
Page 7 of 7