如果ELSE插入,MySQL触发器更新后

时间:2015-05-29 10:19:31

标签: mysql triggers mysql-error-1064

我在装备表中更新triggered后尝试触发插入表格。

它在第7,10和第7行给了我一个checkedOutBy因为我随机改变了一些东西,希望它可能只是神奇地起作用。

Error 1064

2 个答案:

答案 0 :(得分:3)

以下是具有if - elseif

的正确语法的触发器
DELIMITER $$
CREATE TRIGGER moveToHistory AFTER UPDATE ON equip
FOR EACH ROW
BEGIN
IF NEW.checkedOutBy <> Old.checkedOutBy then
   IF OLD.checkedOutBy IS NOT NULL AND NEW.checkedOutBy IS NULL THEN
      INSERT INTO equipmentHistory(assetId, operation, createdBy, creationDate)
      VALUES(new.assetId, 'CheckIn', eid, curdate());
   ELSEIF OLD.checkedOutBy IS NULL AND NEW.checkedOutBy IS NOT NULL THEN
      INSERT INTO equipmentHistory(assetId, operation, createdBy, creationDate)
       VALUES(new.assetId, 'Checkout', eid, curdate());
   END IF;
END IF ;
END;$$

DELIMITER ;

另请注意,我已移除NEW.status = 'CheckedIn';NEW.status = 'CheckedOut';,当您尝试使用after update触发器进行设置时,这些没有意义

答案 1 :(得分:0)

请试试这个

 DELIMITER //

CREATE TRIGGER moveToHistory AFTER UPDATE ON equip
FOR EACH ROW
BEGIN

IF NEW.checkedOutBy != Old.checkedOutBy
BEGIN

IF OLD.checkedOutBy IS NOT NULL AND NEW.checkedOutBy IS NULL THEN
     INSERT INTO equipmentHistory(assetId, operation, createdBy,creationDate)
     VALUES(new.assetId, 'CheckIn', eid, Date(sysdate()))
 NEW.status = 'CheckedIn';
ELSE IF OLD.checkedOutBy IS NULL AND NEW.checkedOutBy IS NOT NULL THEN
 INSERT INTO equipmentHistory(assetId, operation, createdBy, creationDate)
 VALUES(new.assetId, 'Checkout', eid, Date(sysdate()))
 NEW.status = 'CheckedOut';
END IF
END
END
//
DELIMITER ;