简体   繁体   English

MySQL创建触发器语法错误

[英]mysql create trigger syntax error

I've check many SO threads ( one of them here ) but couldn't find where the issue lies. 我检查了许多SO线程( 这里是其中之一 ),但找不到问题所在。

I am trying to protect a column from being updated if it's not null, following this thread . 我试图在此线程之后保护列,如果它不为null则不会被更新。

But I am getting syntax error from mysql. 但是我从mysql中收到语法错误。 Here's my code: 这是我的代码:

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 ;

When you try to raise errors via SIGNAL you need to specify the SQLSTATE which is the error code and for the user defined generic error codes its 45000 along with the message text MESSAGE_TEXT 当您尝试通过SIGNAL引发错误时,您需要指定SQLSTATE作为错误代码,对于用户定义的通用错误代码,其45000以及消息文本MESSAGE_TEXT

So the trigger becomes as 所以触发变成

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 ;

Test Case 测试用例

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

Lets create the trigger now 现在让我们创建触发器

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

And after running the above 2 update commands here how the table looks 在运行上面的2条更新命令之后,表的外观如何

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

Note that the 2nd update failed and the row is unchanged. 请注意,第二次更新失败,并且该行未更改。

Read more about this https://dev.mysql.com/doc/refman/5.5/en/signal.html 进一步了解此https://dev.mysql.com/doc/refman/5.5/en/signal.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM