2016-11-08 80 views
0

你好我的觸發器有問題,當我單獨使用它的時候它可以工作,但一起沒有。如何解決語法錯誤?帶兩個IF模塊的觸發器

CREATE TRIGGER `C_edit` AFTER UPDATE ON `client` 
FOR EACH ROW 
IF OLD.name != NEW.name THEN 
INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name', OLD.id_client, '4', OLD.name, NEW.name); 
END IF; 
IF OLD.name_sql != NEW.name_sql THEN 
INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name_sql', OLD.id_client, '4', OLD.name_sql, NEW.name_sql); 
END IF; 
error: #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 '' at line 4 

回答

0

由於您使用的是觸發體內多條語句,你需要使用MySQL的begin ... end compound statement syntax,與delimiter語句一起改變分隔符:

delimiter // 
CREATE TRIGGER `C_edit` AFTER UPDATE ON `client` 
FOR EACH ROW 
    BEGIN 
     IF OLD.name != NEW.name THEN 
      INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name', OLD.id_client, '4', OLD.name, NEW.name); 
     END IF; 
     IF OLD.name_sql != NEW.name_sql THEN 
      INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name_sql', OLD.id_client, '4', OLD.name_sql, NEW.name_sql); 
     END IF; 
    END// 
delimiter ; 
0

嘗試使用BEGIN/END塊像下面:

DELIMITER $$ 
CREATE TRIGGER `C_edit` AFTER UPDATE ON `client` 
    FOR EACH ROW 
BEGIN 
IF OLD.name != NEW.name THEN 
    INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name', OLD.id_client, '4', OLD.name, NEW.name); 
END IF; 
IF OLD.name_sql != NEW.name_sql THEN 
    INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name_sql', OLD.id_client, '4', OLD.name_sql, NEW.name_sql); 
END IF; 
END $$ 
DELIMITER; 

或無定界符

CREATE TRIGGER `C_edit` AFTER UPDATE ON `client` 
    FOR EACH ROW 
BEGIN 
IF OLD.name != NEW.name THEN 
    INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name', OLD.id_client, '4', OLD.name, NEW.name); 
END IF; 
IF OLD.name_sql != NEW.name_sql THEN 
    INSERT INTO `change`(`id_user`, `table`, `column`, `id`, `status`, `before`, `now`) VALUES (OLD.id_user_edit, 'client', 'name_sql', OLD.id_client, '4', OLD.name_sql, NEW.name_sql); 
END IF; 
END 

PHPMyAdmin不需要DELIMITER,而MySQL Workbench和其他人可以。

+0

因爲您可以配置在phpmyadmin gui和phpmyadmin上使用的分隔符,併爲您在後臺重置分隔符。 :) – Shadow