Can we maintain multiple transactions inside a procedure?

1.7K    Asked by JulianSpringer in SQL Server , Asked on Jan 7, 2020
Answered by Rachit Gupta

Multiple/ nested transaction can be maintained by the transaction inside a transaction, below is the sample for the statement for the same, below is the diagram which explains, if we have nested transaction how are they executed: i.e. first transaction 3 will be committed, post that transaction 2, at the end transaction 1:


Below is the example for the same

create PROC usp_transaction_handle_multiple

AS

BEGIN

  BEGIN try

 BEGIN transaction trans1

   INSERT INTO input_values

   SELECT 'One', 'Two'

      BEGIN try

      BEGIN transaction trans2

      IF (( SELECT count(1) FROM input_values where col1='One') < 2>

           BEGIN

                  UPDATE input_values SET col2 ='updated two' WHERE col1='One'

                  COMMIT transaction trans1

                  PRINT 'Commit trans2 done'

           END

    ELSE

           BEGIN

           RAISERROR('No data to update',16,1)

           END

    END try

           BEGIN CATCH

           ROLLBACK transaction trans2

           PRINT 'ROLLBACK trans2 done'

           END CATCH

           IF (@@TRANCOUNT <> 0)

           BEGIN

           COMMIT transaction trans1

           PRINT 'Commit trans1 done'

           END

    END try

    BEGIN CATCH

    ROLLBACK transaction trans1

    PRINT 'ROLLBACK trans1 done'

    END CATCH

END

Executing statemnets:

select * from input_values

go

exec usp_transaction_handle_multiple

go

select * from input_values




Your Answer

Answer (1)

Yes, it is possible to maintain multiple transactions inside a stored procedure, but this largely depends on the database management system (DBMS) you are using, as different DBMSs have different levels of support for nested transactions and transaction management within stored procedures. Here’s how you can handle multiple transactions in some popular DBMSs:


SQL Server

SQL Server supports nested transactions. You can start a transaction within another transaction, but the commit or rollback behavior can be complex. Here’s an example:

CREATE PROCEDURE MultiTransactionProcedure
AS
BEGIN
    BEGIN TRANSACTION Tran1
    BEGIN TRY
        -- Your first set of operations
        INSERT INTO Table1 (Column1) VALUES ('Value1');
        -- Nested transaction
        BEGIN TRANSACTION Tran2
        BEGIN TRY
            -- Your second set of operations
            INSERT INTO Table2 (Column1) VALUES ('Value2');
            COMMIT TRANSACTION Tran2;
        END TRY
        BEGIN CATCH
            ROLLBACK TRANSACTION Tran2;
            THROW;
        END CATCH;
        COMMIT TRANSACTION Tran1;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION Tran1;
        THROW;
    END CATCH;
END;

PostgreSQL

PostgreSQL supports savepoints, which allow you to create rollback points within a transaction. This is useful for handling partial rollbacks within a single transaction:

CREATE OR REPLACE FUNCTION multi_transaction_function()
RETURNS void AS $$
BEGIN
    BEGIN;
    -- First set of operations
    INSERT INTO table1 (column1) VALUES ('Value1');

    SAVEPOINT savepoint1;
    BEGIN
        -- Second set of operations
        INSERT INTO table2 (column1) VALUES ('Value2');
    EXCEPTION
        WHEN OTHERS THEN
            ROLLBACK TO savepoint1;
            -- Handle exception
    END;
    COMMIT;
END;
$$ LANGUAGE plpgsql;

MySQL

MySQL does not support nested transactions in the way SQL Server does, but you can use a similar approach with savepoints:

DELIMITER //
CREATE PROCEDURE MultiTransactionProcedure()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK      -- Handle the exception
    END;
    START TRANSACTION;
    -- First set of operations
    INSERT INTO Table1 (Column1) VALUES ('Value1');
    SAVEPOINT sp1;
    -- Second set of operations
    BEGIN
        -- If an error occurs here, we can rollback to savepoint sp1
        INSERT INTO Table2 (Column1) VALUES ('Value2');
    END;
    -- More operations
    SAVEPOINT sp2;
    -- Third set of operations
    BEGIN
        -- If an error occurs here, we can rollback to savepoint sp2
        INSERT INTO Table3 (Column1) VALUES ('Value3');
    END;
    COMMIT;
END //
DELIMITER ;Oracle

Oracle also supports savepoints within a single transaction, similar to PostgreSQL and MySQL:

CREATE OR REPLACE PROCEDURE MultiTransactionProcedure IS

BEGIN
    -- Start the main transaction
    SAVEPOINT sp_start;
    BEGIN
        -- First set of operations
        INSERT INTO Table1 (Column1) VALUES ('Value1');
        SAVEPOINT sp1;
        BEGIN
            -- Second set of operations
            INSERT INTO Table2 (Column1) VALUES ('Value2');
        EXCEPTION
            WHEN OTHERS THEN
                ROLLBACK TO sp1;
                -- Handle exception
        END;
        SAVEPOINT sp2;
        BEGIN
            -- Third set of operations
            INSERT INTO Table3 (Column1) VALUES ('Value3');
        EXCEPTION
            WHEN OTHERS THEN
                ROLLBACK TO sp2;
                -- Handle exception
        END;
    EXCEPTION
        WHEN OTHERS THEN
            ROLLBACK TO sp_start;
            -- Handle exception
    END;
    COMMIT;
END;

Key Points to Remember

Transaction Control: Always ensure proper transaction control by using COMMIT and ROLLBACK statements appropriately.

Error Handling: Use try-catch blocks or equivalent constructs to handle errors and perform rollbacks where necessary.

Savepoints: Utilize savepoints to create rollback points within a transaction, enabling finer control over transaction management.

By following these principles and understanding the specific capabilities of your DBMS, you can effectively manage multiple transactions within stored procedures.


5 Months

Interviews

Parent Categories