SQL: Try/Catch doesn't catch an error when attempting to access a table that it can't find

前端 未结 2 1059
感动是毒
感动是毒 2021-01-04 22:20

I\'ve created a stored procedure that runs a number of commands to modify data. I only want to commit the transaction if everything succeeds. I\'m doing this by using a try-

相关标签:
2条回答
  • 2021-01-04 23:05
    EXECUTE ('SELECT * FROM NonexistentTable');
    
    0 讨论(0)
  • 2021-01-04 23:08

    At the start of your script use SET XACT_ABORT

    SET XACT_ABORT ON
    

    When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.

    I don't think that's going to be possible:

    The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:

    • Compile errors, such as syntax errors, that prevent a batch from running.

    • Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.

    Ref.

    The following example shows how an object name resolution error generated by a SELECT statement is not caught by the TRY…CATCH construct, but is caught by the CATCH block when the same SELECT statement is executed inside a stored procedure.

    USE AdventureWorks2012;
    GO
    
    BEGIN TRY
        -- Table does not exist; object name resolution
        -- error not caught.
        SELECT * FROM NonexistentTable;
    END TRY
    BEGIN CATCH
        SELECT 
            ERROR_NUMBER() AS ErrorNumber
            ,ERROR_MESSAGE() AS ErrorMessage;
    END CATCH
    

    The error is not caught and control passes out of the TRY…CATCH construct to the next higher level.

    0 讨论(0)
提交回复
热议问题