How do you use the RAISEERROR function to generate a custom error message in SQL Server?
Posted by LeoRobs
Last Updated: June 21, 2024
In SQL Server, the RAISEERROR function is used to generate a custom error message and can also set the severity level and state of the error. This is useful for error handling and debugging within stored procedures, triggers, or scripts. Here's the general syntax of the RAISEERROR function:
RAISEERROR (message_string, severity, state)
- message_string: This is the custom error message you want to display. It can be a string literal or a variable. - severity: This is a number from 0 to 25 that indicates the type of error. Severity levels from 0 to 10 are typically informational messages, and levels from 11 to 16 are user-defined errors. Levels above 16 indicate system-generated errors. - state: This is an integer value from 0 to 255 that indicates the state or reason for the error. This value is user-defined and can help to differentiate errors.
Example Usage
Here’s a basic example of how to use RAISEERROR:
BEGIN TRY
    -- Simulating a scenario that causes an error
    DECLARE @SomeValue INT = 10;

    IF @SomeValue < 20
    BEGIN
        -- Raise a custom error
        RAISEERROR ('The value must be at least 20.', 16, 1);
    END
END TRY
BEGIN CATCH
    -- Catch the error and display it
    SELECT ERROR_MESSAGE() AS ErrorMessage, ERROR_SEVERITY() AS Severity;
END CATCH;
Explanation of the Example:
1. BEGIN TRY/END TRY: This block contains the code that might raise an error. 2. IF statement: The condition that checks if the variable @SomeValue is less than 20. 3. RAISEERROR: If the condition is met, a custom error message is raised with a severity of 16 and a state of 1. This effectively stops the execution at this point and transfers control to the CATCH block. 4. BEGIN CATCH/END CATCH: This block is executed when an error occurs in the TRY block. Here, we are just selecting the error message and severity from the ERROR_MESSAGE() and ERROR_SEVERITY() functions for display.
Note:
- SQL Server does not stop the execution of the script immediately when encountering RAISEERROR. The error is raised, and execution is transferred to the CATCH block if one exists, or it can be handled by the calling application. - If you wish to terminate the batch or transaction, consider using THROW instead of RAISEERROR. THROW is typically used for re-throwing exceptions in the CATCH block. This is a good way to handle errors gracefully and provide meaningful feedback to users or developers about what went wrong in the application.
Related Content