如何使用基于旧数据和新数据的条件创建更新触发器?

时间:2016-06-01 19:41:15

标签: sql triggers mariadb

我想在何时更新字段server_prev_level_xp NEW.server_xp > OLD.server_prev_level_xp

我使用MariaDb和他的documentation

我试试这个,但它不起作用:

CREATE TRIGGER Level_Update
AFTER UPDATE OF server_xp ON servers
FOR EACH ROW
WHEN (NEW.server_xp > OLD.server_prev_level_xp)
BEGIN
    SET NEW.server_prev_level_xp = OLD.server_prev_level_xp + OLD.server_prev_level_xp >> 1;
    SET NEW.server_level = OLD.server_level + 1;
END;

第4行出错:

WHEN (NEW.server_xp > OLD.server_prev_level_xp)

我做错了什么?

2 个答案:

答案 0 :(得分:1)

用于创建触发器的语法不适用于MariaBD([OF <trigger Column list>]FOR EACH ROW [WHEN (search condition)])。请参阅CREATE TRIGGER

一种选择是使用IF Statement

请记住: Such a SET statement has no effect in an AFTER trigger because the row change will have already occurred.

DELIMITER //

CREATE TRIGGER `Level_Update` /*AFTER*/ BEFORE UPDATE ON `servers`
FOR EACH ROW
BEGIN
  IF NEW.`server_xp` > OLD.`server_prev_level_xp` THEN
  .
  .
  .
  END IF;
END//

DELIMITER ;

答案 1 :(得分:0)

使用此:

DELIMITER //

CREATE TRIGGER `Level_Update` BEFORE UPDATE ON shp_servers
FOR EACH ROW
BEGIN
    IF NEW.`server_xp` > OLD.`server_level_xp` THEN
        SET NEW.`server_level_xp` = OLD.`server_level_xp` + OLD.`server_level_xp` >> 1;
    END IF;
END//

DELIMITER ;

有:

1419 - 您没有SUPER权限并且启用了二进制日志记录(可能想要使用安全性较低的log_bin_trust_function_creators变量)

尝试:

CREATE TRIGGER `Level_Update` BEFORE UPDATE ON shp_servers
    FOR EACH ROW
    BEGIN
        IF NEW.`server_xp` > OLD.`server_level_xp` THEN
            SET NEW.`server_level_xp` = OLD.`server_level_xp` + OLD.`server_level_xp` >> 1;
        END IF;
    END

有:

1064 - 您的SQL语法出错;在第5行