简体   繁体   中英

How to use 'for statement' triggers in postgres?

if we write a trigger FOR STATEMENT like below how can we access only updated rows in trigger procedure/function

CREATE FUNCTION func1()
RETURNS trigger AS $$
BEGIN
    --access only updated/inserted rows here???
    RETURN null;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trig1
AFTER UPDATE OR DELETE OR INSERT
ON tbl1 FOR STATEMENT
EXECUTE PROCEDURE func1();

I mean when there are multiple rows updated once like below

update tbl1 set col1=1 where col2 in (2,3,4,5,6)

Now, it is possible to use an identifier for the table of inserted records in pg 10 :

CREATE TRIGGER transfer_insert
AFTER INSERT ON transfer
REFERENCING NEW TABLE AS inserted
FOR EACH STATEMENT
EXECUTE PROCEDURE check_transfer_balances_to_zero();

Extracted from pg 10 doc : https://www.postgresql.org/docs/10/static/sql-createtrigger.html

At this time there is no support for NEW and OLD pseudo-relations for FOR EACH STATEMENT triggers.

You must use FOR EACH ROW triggers.

In theory it's possible for PostgreSQL to have fake tables for the new- and old- row versions, connected together by some one-off generated key. Or a single table containing the new and old tuples as composite types. However, this is not currently supported, and as far as I know nobody is working on support for it.

For some applications it can be worth using FOR EACH ROW triggers to INSERT into a TEMPORARY table, then process the whole lot in a final FOR EACH STATEMENT trigger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM