mysql : Throw an exception inside procedure

标签 mysql stored-procedures exception

下面的代码应该在金额为负数时抛出异常:

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

你能帮我吗?

最佳答案

检查 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

关于mysql : Throw an exception inside procedure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736828/

相关文章:

php - MySQL 匹配 - 在 bool 模式下?

c# - 如何区分致命和非致命的 .NET 异常

c# - 如果我在属性的 getter 中抛出异常,是否可以在 catch block 中获取属性的名称?

sql - 如何从存储过程 (ADO.NET) 中检索标量值

sql-server - 在 SQL Server 中插入后获取 ID

c# - 如何区分 BackgroundWorker.RunWorkerCompleted 事件处理程序中的不同异常类型

mysql - 使用Parent ID获取所有子节点

php - 如何列出所有 mySQL 记录并为每条记录提供更新按钮?

mysql - 创建表时时间字段发生变化

MySQL 存储过程的数组输入