使用REPLACE()触发器中的MySQL语法错误

时间:2014-09-02 19:41:26

标签: mysql replace triggers syntax-error

如果这个问题已经得到解答,我会先道歉,我尝试了搜索,但无法找到这个具体问题。我正在尝试创建两个触发器,这些触发器将在字段中查找特定的字符串模式,称为' keyword'并用不同的替换它。我现在已经使用了几个小时,没有留下任何头发。有人能告诉我它是做错了吗?

DELIMITER $$
CREATE TRIGGER override_new_alias
BEFORE INSERT ON url_alias
Begin
    set NEW.keyword = replace(NEW.keyword, "store-", "store/");
    set NEW.keyword = replace(NEW.keyword, "genre-", "genre/");
    set NEW.keyword = replace(NEW.keyword, "author-", "author/");
End$$
DELIMITER ;


DELIMITER $$
CREATE TRIGGER override_edit_alias
AFTER update ON url_alias
Begin
    set OLD.keyword = replace(OLD.keyword, "store-", "store/");
    set OLD.keyword = replace(OLD.keyword, "genre-", "genre/");
    set OLD.keyword = replace(OLD.keyword, "author-", "author/");
End$$
DELIMITER ;

这是我得到的.....

MySQL说:文档

#1064 - 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
    set NEW.keyword = replace(NEW.keyword, "store-", "store/");
    set NEW.ke' at line 3 

提前致谢。

1 个答案:

答案 0 :(得分:1)

FIRST TRIGGER

您在第一次触发中忘记了FOR EACH ROW

DELIMITER $$
CREATE TRIGGER override_new_alias
BEFORE INSERT ON url_alias
FOR EACH ROW
Begin
    set NEW.keyword = replace(NEW.keyword, "store-", "store/");
    set NEW.keyword = replace(NEW.keyword, "genre-", "genre/");
    set NEW.keyword = replace(NEW.keyword, "author-", "author/");
End$$
DELIMITER ;

SECOND TRIGGER

请注意,由于提交了所有更改的列,因此无法替换AFTER UPDATE中的任何值。即使AFTER UPDATE触发器编译,它也会在执行时失败。为什么?

根据the Book

MySQL Stored Procedure Programming

第11章Page 251第3段说明如下:

  

BEFOREAFTER触发器之间最显着的区别是,在AFTER中,您无法修改要插入或更新相关表格的值 - - DML已经执行,现在尝试改变DML将要做的事情为时已晚。