Postgresql使用触发器在插入值后更新列值

ffvjumwh  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(2)|浏览(256)

我想在tableA中插入值,然后更新列[amount_hkd]。我已经成功地使用了触发器,但是性能很慢,在应用触发器后,需要一个小时才能完成8400行的插入。我如何提高性能?谢谢你的帮助
要执行的语句:

INSERT INTO tableA (suppliers, invoice_dates, shipment_dates, amounts, currency, currency_conversion_rate)
SELECT l.supplier, l.invoice_date, l.shipment_date, l.amount, l.currency, o.currency_conversion_rate
FROM tableB l
LEFT JOIN tableC o
ON l.currency = o.currency_code
WHERE l.supplier = 'ABC'

我创建的函数:

CREATE OR REPLACE FUNCTION cal() 
RETURNS TRIGGER AS $$ 
BEGIN 
UPDATE tableA 
SET amount_hkd = NEW.amounts * NEW.currency_conversion_rate;
RETURN NEW; 
END; 
$$ LANGUAGE plpgsql;

我尝试的第一个触发器:

CREATE CONSTRAINT TRIGGER update_amount
AFTER INSERT ON tableA
DEFERRABLE
INITIALLY DEFERRED
FOR EACH ROW 
EXECUTE PROCEDURE cal();

我尝试的第二个触发器:

CREATE TRIGGER update_amount 
AFTER INSERT ON tableA
FOR EACH ROW 
EXECUTE PROCEDURE cal();
h5qlskok

h5qlskok1#

在插入行之后更新它是非常低效的。更好的方法是使用BEFORE触发器,它可以在插入新行 * 之前 * 修改它:

CREATE OR REPLACE FUNCTION cal() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN 
   NEW.amount_hkd := NEW.amounts * NEW.currency_conversion_rate;
   RETURN NEW; 
END;$$;

CREATE TRIGGER update_amount 
   BEFORE INSERT ON tableA FOR EACH ROW 
   EXECUTE PROCEDURE cal();
epfja78i

epfja78i2#

您没有指定Postgres版本,但是如果至少是V12,您可以完全避免触发器。将列amount_hkd定义为生成列。您不仅避免了触发器,而且还消除了更新currency_conversion_rate和/或amount以及忘记更新amount_hkd或直接更新amount_hkd的维护问题。类似于:(请参阅example here

create table table_a( a_id integer generated always as identity 
                    , amounts  decimal
                    , currency_conversion_rate decimal
                    , amount_hkd decimal generated always as ( amounts * currency_conversion_rate ) stored
                    );

相关问题