2012-01-28 119 views
1

我建議觸發:MySQL的觸發器定義 - 1064錯誤

#START TRIGGER 
delimiter // 
DECLARE msg VARCHAR(255); 
CREATE TRIGGER passStandard_check BEFORE INSERT ON Module 
FOR EACH ROW 
BEGIN 
IF NEW.passStandard < 0 || NEW.passStandard > 1 THEN 
set msg = concat('Trigger Error: Pass Standard: ', cast(NEW.passStandard as char)); 
signal sqlstate '45000' set message_text = msg; 
END 
// 
delimiter ; 
#END TRIGGER 

,但我得到了以下錯誤:

Error Code: 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 'DECLARE msg VARCHAR(255); CREATE TRIGGER passStandard_check BEFORE INSERT ON Mod' at line 1

添加在END IF沒有任何區別。

passStandard設置爲INT NOT NULL


編輯

我以後移動DECLARE聲明BEGIN

#START TRIGGER 
delimiter // 
CREATE TRIGGER passStandard_check BEFORE INSERT ON Module 
FOR EACH ROW 
BEGIN 
DECLARE msg VARCHAR(255); 
IF NEW.passStandard < 0 || NEW.passStandard > 1 THEN 
set msg = concat('Trigger Error: Pass Standard: ', cast(NEW.passStandard as char)); 
signal sqlstate '45000' set message_text = msg; 
END IF; 
END 
// 
delimiter ; 
#END TRIGGER 

但我仍然得到這個錯誤:

Error Code: 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 'sqlstate '45000' set message_text = msg; END IF; END' at line 7

回答

2

需要聲明的變量在程序中使用「msg」並使用END IF

#START TRIGGER 
delimiter // 
CREATE TRIGGER passStandard_check BEFORE INSERT ON Module 
FOR EACH ROW 
BEGIN 
    DECLARE msg VARCHAR(255); /* << PUT THIS HERE */ 
    IF NEW.passStandard < 0 || NEW.passStandard > 1 THEN 
     set msg = concat('Trigger Error: Pass Standard: ', cast(NEW.passStandard as char)); 
     signal sqlstate '45000' set message_text = msg; 
    END IF; /* << YOU WILL NEED THIS TOO (DONT FORGET THE SEMICOLON :D) */ 
END// 
delimiter ; 
#END TRIGGER 
+0

不,不是這樣。 (另請參閱@clime的答案) – 2012-01-28 01:48:28

+0

「END IF」後面的分號錯過 – 2012-01-28 01:54:44

+0

不用哈哈。我已經添加了分號並更新了錯誤(雖然同樣的錯誤) – 2012-01-28 01:58:55

0

試着將其分解爲多個查詢。或者在phpmyadmin中處理分號分隔的多查詢。

0

可能是這樣的:

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

http://dev.mysql.com/doc/refman/5.0/en/declare.html

+0

不,不是這樣。或者至少,不僅如此。查看編輯 – 2012-01-28 01:48:50

0

我發現我越來越MySQL的警告在他們的if/else邏輯添加觸發器時,如果我不加括號的IF語句。不知道爲什麼,但我添加了括號和警告消失。嘗試像這樣:

IF ((NEW.passStandard < 0) || (NEW.passStandard > 1)) THEN 
    set msg = concat('Trigger Error: Pass Standard: ', cast(NEW.passStandard as char)); 
    signal sqlstate '45000' set message_text = msg; 
END IF; 
0

我知道它的工作。請在下面找到工作代碼。

delimiter // 
CREATE TRIGGER test_check1 BEFORE INSERT ON employee 
FOR EACH ROW 
BEGIN 
DECLARE msg VARCHAR(255); 
IF (NEW.sync_id = '0') THEN 
SET NEW.name = 'Collect Money'; 
signal sqlstate '45000' set message_text = msg; 
END IF; 
END// 
delimiter ;