mysql创建触发器语法错误

时间:2017-03-16 06:31:24

标签: mysql

我检查了很多SO线程(one of them here),但找不到问题所在。

我试图在this thread之后保护列不被更新,如果它不为空。

但我从mysql收到语法错误。这是我的代码:

DELIMITER $$

CREATE TRIGGER lock_x_id
BEFORE UPDATE ON Games
FOR EACH ROW BEGIN
  IF (old.xid IS NOT NULL) THEN
    SIGNAL 'error';
  END IF;
END$$

DELIMITER ;

1 个答案:

答案 0 :(得分:2)

当您尝试通过SIGNAL引发错误时,您需要指定SQLSTATE这是错误代码,并为用户定义的通用错误代码指定其45000以及消息文本{ {1}}

因此触发器变为

MESSAGE_TEXT

测试用例

delimiter //
create trigger lock_x_id before update on games
for each row
begin
 if old.xid is not null then
   signal SQLSTATE VALUE '45000' SET MESSAGE_TEXT = 'Your custom error message';
 end if;
end;//
delimiter ;

让我们现在创建触发器

mysql> select * from games;
+----+------+------+
| id | xid  | val  |
+----+------+------+
|  1 | NULL |    1 |
|  2 | NULL |    2 |
|  3 | NULL |    3 |
|  4 |    1 |    4 |
|  5 |    2 |    5 |
+----+------+------+

在这里运行上述2个更新命令之后,表格看起来如何

mysql> delimiter //
mysql> create trigger lock_x_id before update on games
    -> for each row
    -> begin
    ->  if old.xid is not null then
    ->    signal SQLSTATE VALUE '45000' SET MESSAGE_TEXT = 'Your custom error message';
    ->  end if;
    -> end;//
Query OK, 0 rows affected (0.05 sec)


mysql> update games set xid = 4 where id = 1;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update games set xid = 5 where id=5;
ERROR 1644 (45000): Your custom error message

请注意,第二次更新失败,行未更改。

详细了解此https://dev.mysql.com/doc/refman/5.5/en/signal.html