Raise an error manually in T-SQL to jump to BEGIN CATCH block

前端 未结 5 946
忘掉有多难
忘掉有多难 2021-02-03 19:12

Is it possible to raise an error in a stored procedure manually to stop execution and jump to BEGIN CATCH block? Some analog of throw new Exception() i

相关标签:
5条回答
  • 2021-02-03 19:29

    You could use THROW (available in SQL Server 2012+):

    THROW 50000, 'Your custom error message', 1
    THROW <error_number>, <message>, <state>
    

    MSDN THROW (Transact-SQL)

    Differences Between RAISERROR and THROW in Sql Server

    0 讨论(0)
  • 2021-02-03 19:32

    You're looking for RAISERROR.

    From MSDN:

    Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

    CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

    0 讨论(0)
  • 2021-02-03 19:43

    THROW (Transact-SQL)

    Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.

    Please refer the below link

    T-SQL Throw Exception

    0 讨论(0)
  • 2021-02-03 19:50

    SQL has an error raising mechanism

    RAISERROR ( { msg_id | msg_str | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]
    

    Just look up Raiserror in the Books Online. But.. you have to generate an error of the appropriate severity, an error at severity 0 thru 10 do not cause you to jump to the catch block.

    0 讨论(0)
  • 2021-02-03 19:52

    you can use raiserror. Read more details here

    --from MSDN

    BEGIN TRY
        -- RAISERROR with severity 11-19 will cause execution to 
        -- jump to the CATCH block.
        RAISERROR ('Error raised in TRY block.', -- Message text.
                   16, -- Severity.
                   1 -- State.
                   );
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;
    
        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();
    
        -- Use RAISERROR inside the CATCH block to return error
        -- information about the original error that caused
        -- execution to jump to the CATCH block.
        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
    END CATCH;
    

    EDIT If you are using SQL Server 2012+ you can use throw clause. Here are the details.

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