我已经创建了一个MySQL函数,并且如果为参数传递的值无效,则会引发错误.在MySQL函数中引发错误的选项有哪些?
MySQL 5.5引入了信号,类似于其他语言中的异常:
http://dev.mysql.com/doc/refman/5.5/en/signal.html
例如,在mysql
命令行客户端中:
mysql> SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Custom error'; ERROR 1644 (45000): Custom error
它实际上是所有三个答案的组合.您调用一个不存在的过程来引发错误,然后声明一个捕获您生成的错误的退出处理程序.下面是一个示例,如果要删除的行设置了外键ID,则使用SQLSTATE 42000(过程不存在)在删除之前抛出错误:
DROP PROCEDURE IF EXISTS decount_test; DELIMITER // CREATE DEFINER = 'root'@'localhost' PROCEDURE decount_test ( p_id bigint ) DETERMINISTIC MODIFIES SQL DATA BEGIN DECLARE EXIT HANDLER FOR SQLSTATE '42000' SELECT 'Invoiced barcodes may not have accounting removed.'; IF (SELECT invoice_id FROM accounted_barcodes WHERE id = p_id ) THEN CALL raise_error; END IF; DELETE FROM accounted_barcodes WHERE id = p_id; END // DELIMITER ;
输出:
call decount_test(123456); +----------------------------------------------------+ | Invoiced barcodes may not have accounting removed. | +----------------------------------------------------+ | Invoiced barcodes may not have accounting removed. | +----------------------------------------------------+
为什么不在VARCHAR
声明的INTEGER
变量中存储?
DELIMITER $$ DROP FUNCTION IF EXISTS `raise_error` $$ CREATE FUNCTION `raise_error`(MESSAGE VARCHAR(255)) RETURNS INTEGER DETERMINISTIC BEGIN DECLARE ERROR INTEGER; set ERROR := MESSAGE; RETURN 0; END $$ DELIMITER ; -- set @foo := raise_error('something failed'); -- or within a query
错误信息是:
不正确的整数值:第1行的列'ERROR''失败'
它并不完美,但它提供了一个非常具有描述性的消息,您不必编写任何扩展DLL.
在MySQL 5中,您可能通过调用不存在的存储过程(CALL raise_error)或将无效值传递给查询(如null到NOT NULL约束字段)来引发错误.以下是Roland Bouman关于在MySQL函数中引发错误的有趣帖子:
http://rpbouman.blogspot.com/2005/11/using-udf-to-raise-errors-from-inside.html