MySQL创建触发器(包括变量)语法

时间:2017-07-13 14:34:22

标签: mysql triggers

使用DELIMITER // DROP TRIGGER IF EXISTS trg_tblOptymaster_AFTER_UPDATE // CREATE TRIGGER trg_tblOptymaster_AFTER_UPDATE AFTER UPDATE ON tblOptyMaster FOR EACH ROW BEGIN DECLARE DateFrom DATE; DECLARE DateTo DATE; SET @DateFrom=DATE_ADD(OLD.DueDate, INTERVAL 6 MONTH); SET @DateTo=DATE_ADD(NEW.DueDate, INTERVAL 6 MONTH); INSERT INTO tblOptyDueDateMovement ( OpportunityCRMID, SnapshotDate, DueDateFrom, DueDateTo, DueDateSlippage_Days, DueDateSlippage_Months, DueDateSlippage_FYs ) VALUES ( NEW.OpportunityCRMID, NEW.SnapshotDate, OLD.DueDate, NEW.DueDate, TIMESTAMPDIFF(DAY,DueDateFrom, DueDateTo), TIMESTAMPDIFF(MONTH,DueDateFrom, DueDateTo), TIMESTAMPDIFF(YEAR,@DateFrom, @DateTo) ) END; // DELIMITER ; 触发器语法遇到一点麻烦,获取:

  

#1064 - 您的SQL语法出错;检查与您的MariaDB服务器版本相对应的手册,以便在' END'附近使用正确的语法。在第30行

......知道它失败了吗?

int n = 4 * (1 - Math.sqrt(Math.random()))

1 个答案:

答案 0 :(得分:0)

我终于做对了,我发现分隔符和语法可能有点令人困惑,因为我一直不使用MySQL:

在VALUES()

之后,我错过了;
DELIMITER //
DROP TRIGGER IF EXISTS trg_tblOptymaster_AFTER_UPDATE //

CREATE TRIGGER trg_tblOptymaster_AFTER_UPDATE AFTER UPDATE ON tblOptyMaster 
FOR EACH ROW BEGIN
 DECLARE DateFrom DATE;
 DECLARE DateTo DATE;

 SET @DateFrom=DATE_ADD(OLD.DueDate, INTERVAL 6 MONTH);
 SET @DateTo=DATE_ADD(NEW.DueDate, INTERVAL 6 MONTH);

 INSERT INTO tblOptyDueDateMovement 
    (
    OpportunityCRMID, 
    SnapshotDate, 
    DueDateFrom, 
    DueDateTo,
    DueDateSlippage_Days,
    DueDateSlippage_Months,
    DueDateSlippage_FYs
    ) 
    VALUES 
    (
    NEW.OpportunityCRMID, 
    NEW.SnapshotDate,
    OLD.DueDate,
    NEW.DueDate,
    TIMESTAMPDIFF(DAY,DueDateFrom, DueDateTo),
    TIMESTAMPDIFF(MONTH,DueDateFrom, DueDateTo),
    TIMESTAMPDIFF(YEAR,@DueDateFrom, @DueDateTo)
    );

END//
DELIMITER ;