MySQL没有捕获错误

时间:2013-03-25 02:30:41

标签: mysql sql exception-handling exit-code

当我尝试删除不存在的行时,为什么此代码没有捕获错误?无论我传入哪个参数作为行的名称,它总是返回“1行已删除”并且不使用退出处理程序。应该只捕获这种类型的错误。

USE yoga;

DROP PROCEDURE IF EXISTS delete_warmup;

DELIMITER //

CREATE PROCEDURE delete_warmup 
(
    warmup_name_param               VARCHAR(100)
)
BEGIN
DECLARE row_not_found       TINYINT DEFAULT FALSE;
DECLARE sql_exception       TINYINT DEFAULT FALSE;

BEGIN
    DECLARE EXIT HANDLER FOR 1329
        SET row_not_found = TRUE;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
        SET sql_exception = TRUE;

    DELETE FROM warmup
    WHERE warmup_name = warmup_name_param;

    SELECT '1 row was deleted.' AS message;
END;

IF row_not_found = TRUE THEN
    SELECT 'Row not deleted - row not found' AS message;
ELSEIF sql_exception = TRUE THEN
    SHOW ERRORS;
END IF;

END//

DELIMITER ;

CALL delete_warmup ('Monkey business');

1 个答案:

答案 0 :(得分:0)

您正在为重复参数使用退出处理程序:http://www.briandunning.com/errors/596,如您指定的那样是1329

也许你应该尝试错误代码1011:http://www.briandunning.com/errors/278

另外,请尝试查找NOT FOUND以及SQLException

另外,尝试将退出处理程序放在begin / end子句之外。

因此您的BEGINEND条款将是

DECLARE EXIT HANDLER FOR 1011
DECLARE EXIT HANDLER FOR SQLEXCEPTION, NOT FOUND
BEGIN
        SET row_not_found = TRUE;
        SET sql_exception = TRUE;

    DELETE FROM warmup
    WHERE warmup_name = warmup_name_param;

    SELECT '1 row was deleted.' AS message; 
END;