Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL - Return custom error message and end query

I have a lengthy stored procedure in which I would like to do something like the following:

IF @SubPageDirectory IS NULL
BEGIN
    RAISERROR('@SubPageDirectory cannot be NULL', 10, 1)
    EXIT STORED PROCEDURE
END

Basically I wish to check whether my variable is NULL, and if it is, return an error message to my .NET Web Application, and stop running the query at that stage. How can I achieve this?

like image 827
Curtis Avatar asked Jul 15 '10 13:07

Curtis


People also ask

How do I return a custom error in SQL?

How to return a custom error message from SQL Server in case of error? To return custom error message in case of error, we pass necessary parameter to the THROW statement. Throw has three parameters, ErrorNumber – must be greater than 50000 and less than 2147483647.

How do I create a custom error message in SQL Server?

Therefore, when a system error occurs, SQL Server will log a system error and may take actions to fix the error. Custom errors, on the other hand, are generated by T-SQL custom codes based on your code or business logic. To add a custom error message to sys. messages, the stored procedure sp_addmessage is used.

How do I display an error message in SQL?

When called in a CATCH block, ERROR_MESSAGE returns the complete text of the error message that caused the CATCH block to run. The text includes the values supplied for any substitutable parameters - for example, lengths, object names, or times. ERROR_MESSAGE returns NULL when called outside the scope of a CATCH block.

Does Raiserror stop execution?

By itself, RAISERROR does not cause an exit from the procedure, but it can be combined with a RETURN statement or a test of the @@error global variable to control execution following a user-defined error. If you set the ON_TSQL_ERROR database option to CONTINUE, RAISERROR no longer signals an execution-ending error.


1 Answers

IF @SubPageDirectory IS NULL 
BEGIN 
    RAISERROR('@SubPageDirectory cannot be NULL', 16, 1) --change to > 10
    RETURN --exit now
END 
like image 82
gbn Avatar answered Sep 21 '22 06:09

gbn