gpt4 book ai didi

postgresql - 更新 postgres 触发器中的值

转载 作者:行者123 更新时间:2023-11-29 13:04:22 25 4
gpt4 key购买 nike

我试图在其他一些列发生变化时计算列上的值,因此我创建了一个类似这样的触发器。我的“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();

最佳答案

这是因为当您需要 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
)
...

关于postgresql - 更新 postgres 触发器中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18641657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com