Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RETURN inside a transaction with TRY-CATCH block

I have the following code, and I am wondering, as a generic example, if the transaction is left open if it exits with RETURN.

BEGIN TRANSACTION
    BEGIN TRY
        IF NOT EXISTS(SELECT 1 FROM dbo.tblProducts WHERE intProductID = @intProductID)
            BEGIN
                SELECT 'Product does not exists' AS strMessage
                RETURN
            END

        UPDATE dbo.tblProducts SET
            curPrice = 10
        WHERE
            intProductID = @intProductID

        SELECT 'Success' AS strMessage

    END TRY 

    BEGIN CATCH
        SELECT ERROR_MESSAGE() AS strMessage
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION
    END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION
like image 957
user1185775 Avatar asked Aug 18 '12 21:08

user1185775


People also ask

Is it correct best practice to have the try catch block inside the transaction or should the transaction be inside the try block?

Option A is the correct choice. It is possible for all statements in a transaction to work and then the actual COMMIT to fail, so you keep the COMMIT inside your TRY block so that any failure of the COMMIT will be caught and you can gracefully handle this error and rollback.

How do you use begin transaction and rollback with try and catch in SQL Server?

In the TRY block a transaction is started and the two UPDATE statements are performed. If both UPDATEs succeed, the COMMIT will be reached and the transaction committed. If, however, either one produces an error, control will be execute CATCH block where the transaction will be rolled back.

What is @@ Transcount in SQL Server?

@@TRANCOUNT (Transact-SQL)Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.

Does Procedure Support try catch block?

If the stored procedure contains a TRY... CATCH construct, the error transfers control to the CATCH block in the stored procedure. When the CATCH block code finishes, control is passed back to the statement immediately after the EXECUTE statement that called the stored procedure.


1 Answers

It should be like Below

BEGIN TRY
    SET NOCOUNT ON
    SET XACT_ABORT ON
    BEGIN TRANSACTION
        IF NOT EXISTS(SELECT 1 FROM dbo.tblProducts 
                          WHERE intProductID = @intProductID)
        BEGIN
            SELECT 'Product does not exists' AS strMessage
            Rollback TRan
            RETURN
        END

        UPDATE dbo.tblProducts SET
        curPrice = 10
        WHERE
        intProductID = @intProductID

        SELECT 'Success' AS strMessage
    COMMIT TRAN
END TRY 

BEGIN CATCH
    SELECT ERROR_MESSAGE() AS strMessage
    ROLLBACK TRANSACTION
END CATCH
like image 111
Pankaj Avatar answered Oct 11 '22 01:10

Pankaj