为 MySQL 数据库中的表创建触发器(语法错误)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/469784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating trigger for table in MySQL database (syntax error)
提问by Georg Ledermann
I have trouble defining a trigger for a MySQL database. I want to change a textfield before inserting a new row (under a given condition). This is what I have tried:
我无法为 MySQL 数据库定义触发器。我想在插入新行之前更改文本字段(在给定条件下)。这是我尝试过的:
CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
IF (NEW.sHeaders LIKE "%[email protected]%") THEN
SET NEW.sHeaders = NEW.sHeaders + "BCC:[email protected]";
END IF;
END;
But always I get the error "wrong syntax". I got stuck, what am I doing wrong? I'm using MySQL 5.0.51a-community
但我总是收到错误“语法错误”。我被卡住了,我做错了什么?我正在使用MySQL 5.0.51a-community
BTW: Creating an empty Trigger like this works fine:
顺便说一句:像这样创建一个空的触发器工作正常:
CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
END;
But this fails, too:
但这也失败了:
CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
IF 1=1 THEN
END IF;
END;
It's my first time to use stackoverflow.com, so I'm very excited if it is helpful to post something here :-)
这是我第一次使用 stackoverflow.com,所以如果在这里发布一些东西有帮助,我很兴奋:-)
回答by Greg
You need to change the delimiter- MySQL is seeing the first ";" as the end of the CREATE TRIGGER statement.
您需要更改分隔符- MySQL 看到第一个“;” 作为 CREATE TRIGGER 语句的结尾。
Try this:
尝试这个:
/* Change the delimiter so we can use ";" within the CREATE TRIGGER */
DELIMITER $$
CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
IF (NEW.sHeaders LIKE "%[email protected]%") THEN
SET NEW.sHeaders = NEW.sHeaders + "BCC:[email protected]";
END IF;
END$$
/* This is now "END$$" not "END;" */
/* Reset the delimiter back to ";" */
DELIMITER ;