2014-09-02 121 views
0

如果這個問題已經被回答,我會先道歉,我試過搜索,但找不到這個特定的問題。我試圖創建兩個觸發器,它們會在名爲'keyword'的字段中查找特定的字符串模式,並用另一個替換它。我現在已經用了幾個小時,沒有留下任何頭髮。有人能告訴我我做錯了什麼嗎?用REPLACE觸發的MySQL語法錯誤()

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

第一個觸發

你在第一個觸發忘記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 ; 

第二個觸發

請注意,由於一切都改變了列承諾你不能在一個替換的任何值更新後。即使AFTER UPDATE觸發器編譯,它也會在執行時失敗。爲什麼?

根據the Book

MySQL Stored Procedure Programming

第11章第251第3款說以下內容:

BEFOREAFTER觸發器之間最顯著不同的是,在AFTER你不能修改要插入或更新的值--DML已執行,試圖更改DML的內容爲時已晚 將要做。