Skip to main content

SQL - Try Catch Rollback

BEGIN TRY
    BEGIN TRANSACTION;

    -- SQL statements that are part of the transaction
    -- e.g., INSERT, UPDATE, DELETE statements

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    -- Error handling logic
    IF @@TRANCOUNT > 0
    BEGIN
        ROLLBACK TRANSACTION;
    END;

    -- Optional: Log error details, raise error, or perform other actions
    SELECT ERROR_MESSAGE() AS ErrorMessage,
           ERROR_SEVERITY() AS ErrorSeverity,
           ERROR_STATE() AS ErrorState,
           ERROR_LINE() AS ErrorLine,
           ERROR_PROCEDURE() AS ErrorProcedure;

    -- Optional: Re-throw the error
    -- THROW;
END CATCH;