Mysql Trigger将记录插入到特定列更新的另一个表中

时间:2014-07-21 19:28:37

标签: mysql sql

好吧,我正在尝试在MySQL中创建一个触发器,它将表中的旧日期插入到另一个表中以跟踪发生的更改。我有以下表格。我无法更改用户表,但我可以更改user_changes表。我在下面创建了这个触发器,但它在插入语句的行上一直给我一个错误。

  

用户:id,StoreNbr,UserNbr,LvlNbr,Paid1,Paid2   user_changes:id,store_nbr,user_number,level_number,OldPaid1,OldPaid2,create

DROP TRIGGER IF EXISTS usersToChanges;
CREATE TRIGGER `usersToChanges` AFTER UPDATE ON users FOR EACH ROW
BEGIN
IF LENGTH(CONV(NEW.Status, 10, 2)) NOT IN (5,6,8) AND (NOT(NEW.Paid1 <=> OLD.Paid1) OR NOT(NEW.Paid2 <=> OLD.Paid2)) 
    THEN
        INSERT INTO user_changes (store_nbr, user_number, level_number, OldPaid1, OldPaid2, created) 
        VALUES (OLD.StoreNbr, OLD.UserNbr, OLD.LvlNbr, OLD.Paid1, OLD.Paid2, NOW());
    END IF;
END;

1 个答案:

答案 0 :(得分:1)

您需要使用DELIMTER command来定义过程代码:

DROP TRIGGER IF EXISTS usersToChanges;
DELIMITER $$
CREATE TRIGGER `usersToChanges` AFTER UPDATE ON users FOR EACH ROW
BEGIN
IF LENGTH(CONV(NEW.Status, 10, 2)) NOT IN (5,6,8) AND (NOT(NEW.Paid1 <=> OLD.Paid1) OR NOT(NEW.Paid2 <=> OLD.Paid2)) 
    THEN
        INSERT INTO user_changes (store_nbr, user_number, level_number, OldPaid1, OldPaid2, created) 
        VALUES (OLD.StoreNbr, OLD.UserNbr, OLD.LvlNbr, OLD.Paid1, OLD.Paid2, NOW());
    END IF;
END $$
DELIMITER ;

分号通常用于分隔单个命令,而不是过程代码。请注意我如何将END;更改为END $$以完成触发操作。然后,我切换回分号的默认分隔符。