mysql触发结束如果语法错误

lsmd5eda  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(273)

无法在更新特定字段时创建触发器

delimiter //
CREATE TRIGGER `add_event` AFTER  UPDATE ON `order_table` 
  FOR EACH ROW 
  IF NEW.status <=> OLD.status THEN
    INSERT INTO `events` SET 
      events.status = NEW.status, 
      events.order_id = NEW.order_id, 
      events.time_stamp = CURRENT_TIMESTAMP
  END IF;
delimiter ;

我得到这个错误
1064-您的sql语法有错误;检查与您的mysql服务器版本相对应的手册,以获得使用near'end if的正确语法;

k4aesqcs

k4aesqcs1#

下面的mysql触发器中没有语法错误。

delimiter //
 CREATE TRIGGER add_event AFTER UPDATE ON order_table
    FOR EACH ROW
    BEGIN
         IF NEW.status <=> OLD.status THEN
            INSERT INTO `events` 
            SET events.status = NEW.status, 
            events.order_id = NEW.order_id, 
            events.time_stamp = CURRENT_TIMESTAMP;
         END IF;
     END;//
 delimiter ;
j2cgzkjk

j2cgzkjk2#

drop table if exists t;
drop table if exists events;

create table t(order_id int, status varchar(1));
create table events(order_id int, time_stamp timestamp,status varchar(1));
drop trigger if exists t;
delimiter //
CREATE TRIGGER t after update ON `t` 
 FOR EACH ROW 
 begin
 IF NEW.status <> OLD.status THEN
    INSERT INTO `events` 
        SET events.status = NEW.status, 
                events.order_id = NEW.order_id, 
                 events.time_stamp = CURRENT_TIMESTAMP;
END IF ;
end //
 delimiter ;

 insert into t values(1,1);
 insert into events values(1,now(),1);
 update t set status = 2 where order_id = 1;
 select * from t;
 select * from events;

MariaDB [sandbox]>  select * from t;
+----------+--------+
| order_id | status |
+----------+--------+
|        1 | 2      |
+----------+--------+
1 row in set (0.00 sec)

MariaDB [sandbox]>  select * from events;
+----------+---------------------+--------+
| order_id | time_stamp          | status |
+----------+---------------------+--------+
|        1 | 2018-08-06 10:16:35 | 1      |
|        1 | 2018-08-06 10:16:35 | 2      |
+----------+---------------------+--------+
2 rows in set (0.00 sec)
k3fezbri

k3fezbri3#

为什么使用if语句。您正在检查所有内容。以下是解决方案:

CREATE TRIGGER `add_event` AFTER  UPDATE ON `order_table` 
 FOR EACH ROW 
 BEGIN
 INSERT INTO `events` SET events.status = NEW.status, events.order_id = NEW.order_id, events.time_stamp = CURRENT_TIMESTAMP;
END;
 delimiter ;

相关问题