表中的乘法触发器

时间:2012-07-28 04:45:22

标签: mysql triggers

我有一个表salesOrderItems:

soItemID           INT(11)         PK
salesOrderID       INT(11)
productID          INT(11)
cost               DECIMAL(7,2)
qty                TINYINT(2)
extendedCost       DECIMAL(8,2)

通过PHP,用户会看到一个表单,用于输入productID(通过下拉列表),然后该选择将填充成本字段。然后用户输入数量。表格中看不到extendedCost

我想要的是一个触发器,应该只是自动计算/插入extendedCost(即 - 乘以成本x数量)并填充extendedCost,但我得到1064个错误。

这里是触发器 - 我到底错过了什么?我发誓我已经完成了20次:

DELIMITER $$

DROP TRIGGER IF EXISTS EXTENDEDCOST $$

CREATE TRIGGER EXTENDEDCOST AFTER INSERT ON salesOrderItems FOR EACH ROW BEGIN

    UPDATE salesOrderItems
    SET extendedCost = (cost * qty)
    WHERE soItemID = NEW.soItemID;

END $$

DELIMITER ;

结果:

ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-db' at line 1

SQL Statement:

USE <my db/schema>



ERROR: Error when running failback script. Details follow.



ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-db' at line 1

SQL Statement:

USE <my db/schema>

我确定这是一件愚蠢的事情,但它让我疯了,我完全卡住了,需要额外的眼睛......

提前谢谢你们!

1 个答案:

答案 0 :(得分:0)

由于您尝试插入计算值,为什么要执行额外更新而不设置触发时间 BEFORE INSERT

CREATE TRIGGER EXTENDEDCOST BEFORE INSERT ON salesOrderItems FOR EACH ROW BEGIN
  SET NEW.extendedCost = NEW.cost * NEW.qty
END $$

另见这个答案mysql 'after insert' trigger to calculate a field based on other fields