我创建了一个表格如下:
mysql> create table testa (a int, b int, c real);
Query OK, 0 rows affected (0.14 sec)
但是当我想实现这样的触发器时,我会遇到一些语法错误:
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
我已在http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html查看了文档,但无法解决问题!
我的MySQL版本:
Server version: 5.5.38-0ubuntu0.12.04.1 (Ubuntu)
根据以下评论,我尝试了以下案例,但也崩溃了:
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
答案 0 :(得分:3)
这里有些不对劲。
这是应该有用的代码!
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 ;
答案 1 :(得分:-1)
此外,您可以使用 select 命令显示任何消息。
IF (NEW.c > 100) THEN
SELECT "Warning: c > 100!" AS Output;
END IF
将上面的代码放在触发器中。它将打印输出