Mysql:在程序中抛出一个异常

时间:2015-11-16 13:42:49

标签: mysql stored-procedures exception-handling

我有以下代码,如果金额为负数,则应抛出异常:

create procedure depositMoney(
        IN acc integer,
        IN amoun integer
    )
    BEGIN
        DECLARE negative CONDITION FOR SQLSTATE '45000';
        IF amoun < 0 THEN SIGNAL negative;
        END IF;
        INSERT INTO account(balance) VALUES amoun where account.number = acc;
    END; 

但是当我执行时我有一个#1064错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 6

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

检查INSERT的语法。

尝试:

DELIMITER //

DROP PROCEDURE IF EXISTS `depositMoney`//

CREATE PROCEDURE `depositMoney` (
  IN `acc` INTEGER,
  IN `amoun` INTEGER
)
BEGIN
  DECLARE `negative` CONDITION FOR SQLSTATE '45000';
  IF `amoun` < 0 THEN
    SIGNAL `negative`
    SET MESSAGE_TEXT = 'An error occurred';
  END IF;
  /*
  Check the syntax of the INSERT.
  INSERT INTO account(balance) VALUES amoun where account.number = acc;
  */
END//

DELIMITER ;

MySQL 5.5或更高版本。

测试:

mysql> CALL `depositMoney`(NULL, -1);
ERROR 1644 (45000): An error occurred