MySQL触发器:当插入的条目大于一个值时打印警告消息

Vah*_*ili 6 mysql database

我创建了一个表,如下所示:

mysql> create table testa (a int, b int, c real);
Query OK, 0 rows affected (0.14 sec)
Run Code Online (Sandbox Code Playgroud)

但是当我想实现这样的触发器时,我会遇到一些语法错误:

mysql> create trigger testa_trig  
       before insert ON testa 
       FOR EACH ROW 
       WHEN (NEW.c > 100) 
       BEGIN 
         Print "Warning: c > 100!"
       END;
ERROR 1064 (42000): 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 'WHEN (NEW.c > 100) 
BEGIN
Print "Warning: c > 100!"
END' at line 4
Run Code Online (Sandbox Code Playgroud)

我已经检查了http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html 上的文档,但无法找出问题所在!

我的 MySQL 版本:

Server version: 5.5.38-0ubuntu0.12.04.1 (Ubuntu)
Run Code Online (Sandbox Code Playgroud)

根据下面的评论,我尝试了以下情况,但也崩溃了:

mysql> create trigger testa_trig before insert on testa for each row 
       if (NEW.c > 100) begin insert into testb set bc=NEW.c end;
ERROR 1064 (42000): 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 'begin insert into testb set bc=NEW.c end' at line 1
Run Code Online (Sandbox Code Playgroud)

Def*_*ral 6

这里有一些错误。

  1. 分隔符。当您创建 MySQL 过程或触发器时,您需要对分隔符非常明确,以便查询解释器可以区分过程中的行尾和声明的结束。
  2. BEGIN 语句的位置。它应该直接在 FOR EACH ROW 之后。
  3. 使用 WHEN 而不是 IF。
  4. 使用 PRINT 代替 SIGNAL SQLSTATE '...' SET MESSAGE_TEXT = '...'。这就是在 MySQL 5.5+ 中引发异常的方式。

这是应该可以工作的代码!

DELIMITER $$

CREATE TRIGGER testa_trig  
BEFORE INSERT ON testa 
FOR EACH ROW BEGIN
    IF (NEW.c > 100) THEN 
        SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning: c > 100!';
    END IF;
END$$

DELIMITER ;
Run Code Online (Sandbox Code Playgroud)