MySQL - 如何在存储过程中抛出异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9131379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:00:41  来源:igfitidea点击:

MySQL - How to throw exception in stored procedure?

mysqlexceptionstored-procedures

提问by Vegetus

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

如何在MySQL的存储过程中产生异常?例如:

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:

在 MySQL 中,我认为没有办法在存储过程中抛出异常,但我可以通过从不存在的表中进行选择来强制错误。例如:

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.

谢谢。

回答by Mchl

Since MySQL 5.5 you can use SIGNALand RESIGNALfor 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).

从 MySQL 5.5 开始,您可以使用SIGNALRESIGNAL进行错误处理。在此之前,没有办法处理 MySQL 中的错误。唯一的方法是运行错误的查询(例如插入到不存在的表中)。

回答by Ulad Kasach

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

以下是如何在 mysql 中抛出异常的示例,该示例适用于 5.5 及更高版本:

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

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

详细信息可以在这里找到:https: //dev.mysql.com/doc/refman/5.5/en/signal.html