我正在尝试构建一个触发器功能,以在任何项目发生变化时自动更新父订单值。
这是我创建的:
CREATE OR REPLACE FUNCTION update_totals() RETURNS void AS $$
UPDATE orders SET
total_fees = (SELECT SUM(fees) FROM order_items WHERE order_id = OLD.order_id),
total_profit = (CASE WHEN total_cost IS NOT NULL THEN total - total_tax - total_cost - (SELECT SUM(fees) FROM order_items WHERE order_id = OLD.order_id) ELSE NULL END)
WHERE id = OLD.order_id;
$$
LANGUAGE SQL;
CREATE TRIGGER update_totals AFTER INSERT
OR UPDATE OF fees
ON order_items INITIALLY DEFERRED
FOR EACH ROW
WHEN ( OLD.* IS DISTINCT FROM NEW.* ) EXECUTE PROCEDURE update_totals();
当我尝试运行它时,我收到此错误:
missing FROM-clause for table "old"
我尝试在触发器中创建对原始表的引用:
CREATE TRIGGER update_totals AFTER INSERT
OR UPDATE OF fees
ON order_items
REFERENCING OLD ROW AS old_order
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
WHEN ( OLD.* IS DISTINCT FROM NEW.* ) EXECUTE PROCEDURE update_totals();
但这只是给出了错误syntax error at or near "REFERENCING"
。
如何order_id
从原始order_items
表中获取?
首先
order_items
,要在表上创建触发器,update_totals()
必须是触发器函数RETURNS TRIGGER
(粗体是我的)。如果不是,则会导致错误
ERROR: function func_order_items must return type trigger
。其次,请记住,您不能在触发器上设置
OLD
何时。AFTER INSERT
如果不是,则会引发错误ERROR: record "old" is not assigned yet
。最后,请看下面的例子: