RAISERROR is used to generate custom error messages in SQL Server with a specified severity and state, commonly used for validations and business rule enforcement.
RAISERROR is used to raise a
custom error message in SQL Server and optionally we can stop execution or roll
back a transaction or log the error or return an error to the application. It is commonly used in stored procedures,
triggers, validations, and business rules.
Syntex
RAISERROR (message, severity,
state)
Severity Levels
|
Severity |
Meaning |
|
0–10 |
Informational |
|
11-16 |
User-defined errors (most common) |
|
17-19 |
Software
/ resource errors |
|
20-25 |
Fatal (connection terminated) |
See the example. For the demo
here we are creating.
|
CREATE TABLE Orders ( OrderID INT IDENTITY, Amount INT ); |
Now we are writing the business
rule that Amount should be greater than 0 , if someone insert less than 0 data
will into inserted and throw an error message.
|
DECLARE @Amount INT = -500; IF @Amount <= 0 BEGIN RAISERROR ('Order amount
must be greater than zero.', 16, 1); RETURN; END INSERT INTO Orders (Amount) VALUES (@Amount); |
Here we are trying to insert
amount less than 0. Let’s run this
Now inserting amount greater than 0.
|
DECLARE
@Amount INT = 500; IF @Amount
<= 0 BEGIN RAISERROR ('Order amount must be greater
than zero.', 16, 1); RETURN; END INSERT INTO
Orders (Amount) VALUES
(@Amount); |
Data inserted successfully.
In this way we throe an error.
No comments:
Post a Comment
If you have any doubt, please let me know.