Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - How to throw exception in stored procedure?

How to generate an exception in the stored procedure in MySQL? For example:

CREATE PROCEDURE SALES() BEGIN  STATEMENT... STATEMENT... STATEMENT...  IF (PRICE >= 500) THEN /** THROWS AN EXCEPTION....       WHAT DO TO STOP THE PROCEDURE. **/ END IF;  STATEMENT... STATEMENT... STATEMENT...  END; 

In MySQL I think there is no way to throw an exception in a stored procedure, but I can force an error by selecting from a non-existing table. For example:

IF (PRICE > 500) THEN     /*throw the error here*/     SELECT * FROM price_greater_than_500_in_throw_exception; END IF; 

Is there a more elegant way?

Thanks.

like image 486
Vegetus Avatar asked Feb 03 '12 15:02

Vegetus


People also ask

How do I throw an exception in MySQL?

CREATE PROCEDURE SALES() BEGIN STATEMENT... STATEMENT... STATEMENT... IF (PRICE >= 500) THEN /** THROWS AN EXCEPTION....

How exceptions are handled in stored procedure?

Raising an Exception in a Stored Procedure To raise an exception in a stored procedure, use the following syntax: EXCEPTION name; where <name> is the name of an exception that already exists in the database.

What is Sqlexception in MySQL?

For SQLEXCEPTION conditions, the stored program terminates at the statement that raised the condition, as if there were an EXIT handler. If the program was called by another stored program, the calling program handles the condition using the handler selection rules applied to its own handlers.

Can we use try catch in MySQL stored procedure?

Instead of wrapping all of your code in a try catch block you basically add what's called a handler to your procedure. Typically you would want to stop executing, and in MySQL that is managed through an exit handler . Depending on the use case you may want to rollback or log the event when the handler is called.


2 Answers

Since MySQL 5.5 you can use SIGNAL and RESIGNAL for error handling. Prior to that there was no way to handle errors in MySQL. Only way is to run an erroneous query (for example inserting into non existing table).

like image 186
Mchl Avatar answered Sep 17 '22 03:09

Mchl


Here is an example of how to throw an exception in mysql, which works on versions 5.5 and above:

SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Custom error'; 

Details can be found here: https://dev.mysql.com/doc/refman/5.5/en/signal.html

like image 34
Ulad Kasach Avatar answered Sep 20 '22 03:09

Ulad Kasach