Calling a function for each updated row in postgresql -


i have sql update statement in plpgsql function. want call pg_notify function each updated row , uncertain if solution best possibility.

i not aware of position in update statement apply function. don't think possible in set part , if apply function in where part, applied each row checked , not updated rows, correct?

i therefore thought use returning part purposes , designed function this:

create or replace function function_name() returns void $body$ begin     update table1     set = true     table2     table1.b = table2.c     , <more conditions>     returning pg_notify('notification_name', table1.pk); end; $body$ language 'plpgsql' volatile; 

unfortunately gave me error saying not using or storing return value of query anywhere. therefore tried putting perform in front of query seemed syntactically incorrect.

after trying different combinations perform ultimate solution this:

create or replace function function_name() returns void $body$ declare     dev_null integer; begin     updated (         update table1         set = true         table2         table1.b = table2.c         , <more conditions>         returning pg_notify('notification_name', table1.pk)     )     select 1 dev_null;  end; $body$ language 'plpgsql' volatile; 

this works supposed to, feel there should better solution not temporarily store useless result , not use useless variable.

thank help.

** edit 1 **

as can seen in @pnorton 's answer, trigger trick in cases. me, however, not applicable receiver of notifications updates table , not want generate notifications in such case

"i have sql update statement in plpgsql function. i want call pg_notify function each updated row "

ok might tempted use trigger eg

    create table foobar (id serial primary key, name varchar);  create or replace function notify_trigger() returns trigger $$ declare begin   perform pg_notify('watch_tb_update', tg_table_name || ',id,' || new.id );   return new; end; $$ language plpgsql;  create  trigger foobar_trigger after insert on foobar each row execute procedure notify_trigger();  listen watch_tb_update;  insert foobar(id, name) values(1,'test_name'); 

i've tested , works fine


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -