在postgres触发器中更新值

时间:2013-09-05 16:37:53

标签: postgresql triggers

当其他一些列发生变化时,我正在尝试计算列上的值,所以我创建了一个类似的触发器。我的'total_points'列总是包含0,所以有些不对劲。我做错了什么?我验证了下面的每个SELECT调用都返回一个非零值。

CREATE FUNCTION update_order_total_points() RETURNS trigger
  LANGUAGE plpgsql
  AS $$
BEGIN
    NEW.total_points = NEW.ud * (SELECT amount FROM points WHERE abbrev = 'ud') +
                       NEW.dp * (SELECT amount FROM points WHERE abbrev = 'dp') +
                       NEW.swrv * (SELECT amount FROM points WHERE abbrev = 'swrv') +
                       NEW.sh * (SELECT amount FROM points WHERE abbrev = 'sh') +
                       NEW.jmsw * (SELECT amount FROM points WHERE abbrev = 'jmsw') +
                       NEW.sw * (SELECT amount FROM points WHERE abbrev = 'sw') +
                       NEW.prrv * (SELECT amount FROM points WHERE abbrev = 'prrv') +
                       NEW.mhsw * (SELECT amount FROM points WHERE abbrev = 'mhsw') +
                       NEW.bmsw * (SELECT amount FROM points WHERE abbrev = 'bmsw') +
                       NEW.mp * (SELECT amount FROM points WHERE abbrev = 'mp') +
                       NEW.pr * (SELECT amount FROM points WHERE abbrev = 'pr') +
                       NEW.st * (SELECT amount FROM points WHERE abbrev = 'st');
    RETURN NEW;
END;
$$;

CREATE TRIGGER fix_total_points
AFTER INSERT OR UPDATE OF ud, dp, swrv, sh, jmsw, sw, prrv, mhsw, bmsw, mp, pr, st
ON orders
FOR EACH ROW EXECUTE PROCEDURE update_order_total_points();

2 个答案:

答案 0 :(得分:1)

它正在运行AFTER INSERT,因此无法修改该行。将其设置为BEFORE触发器。

如果你能想出一种将十五个左右SELECT amount个查询合并为一个的方法,那么它也会更快。

答案 1 :(得分:1)

这是因为当你需要BEFORE触发时,你正在使用AFTER插入触发器。 使用两个触发器检查此sql fiddle demo;

此外,您可以尝试将触发器重写为类似的内容,这样您只需从points表中选择一个:

    ...

    NEW.total_points =
        (
             with cte(amount, abbrev) as (
                 select NEW.ud, 'ud' union all
                 select NEW.dp 'dp' union all
                 select NEW.swrv, 'swrv' union all
                 ...
             )
             select sum(p.amount * t.amount)
             from points as p
                 inner join cte as t on t.abbrev = p.abbrev
        )
    ...