How to use RAISERROR in SQL Server
In SQL Server, the RAISERROR function is used to raise user-defined error messages in stored procedures, triggers, or functions. It has the following syntax:
RAISERROR ({msg_id | msg_str }{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
The parameters are as follows: – msg_id: specifies the message ID of the error message. This can be a pre-defined message ID or a user-defined error message string. – msg_str: specifies a user-defined error message string. – severity: specifies the severity level of the error, which is an integer between 1 and 25, where 1-10 are considered informational messages, 11-16 are warning messages, and 17-25 are severe error messages. – state: specifies the state code of the error, which is an integer between 0 and 255. – argument: specifies one or more replacement parameters that can be used in the error message. The number of parameters depends on the number of placeholders in the error message. – option: specifies additional options, such as formatting options for the FORMATMESSAGE function. Below are some examples of using the RAISERROR function: 1. Raise a user-defined error message.
RAISERROR('This is a user-defined error message', 16, 1)
Generate an error message with a predefined message ID.
RAISERROR(50001, 16, 1)
Trigger an error message with parameters.
DECLARE @param INT = 10;RAISERROR('The parameter value is %d', 16, 1, @param)
The error messages in the above example can be caught and handled by the application or client program.