1

Hello and thanks for taking the time in advance to look at my question. This is my first try at using triggers and functions in PostgreSQL (using DBeaver) and I appreciate your feedback.

I'd like to update a column (village_id) every time a new row is entered or updated with the primary key value of a different table (which is not connected as a foreign key directly). See below for an outline of my tables and trigger + function.

Unfortunately, after using the code below I received an error each time I was entering a new row with information. I used an UPDATE statement, but I also considered using an insert into statement, but wasn't sure what is more preferable. Thank you in advance.

CREATE TABLE register_table
(
  register_id integer CONSTRAINT register_id_pk PRIMARY KEY,
  village_id integer NOT NULL
);

CREATE TABLE er_table
(
  er_id integer CONSTRAINT er_id_pk PRIMARY KEY,
  register_id integer NOT NULL,
  village_id integer NOT NULL
);

CREATE OR REPLACE FUNCTION update_village_id_column()
RETURNS trigger AS
$BODY$
BEGIN

  UPDATE schema_example.er_table
  SET    village_id = register_table.village_id
  FROM   schema_example.register_table
  WHERE  (schema_example.register_id = new.register_id);

  RETURN new; 

END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

CREATE TRIGGER update_village_id
AFTER INSERT OR UPDATE
ON schema_example.er_table
FOR EACH ROW
EXECUTE PROCEDURE update_village_id_column();

EDIT: removed recursive part from trigger

CREATE TRIGGER update_village_id
AFTER INSERT
ON schema_example.er_table
FOR EACH ROW
EXECUTE PROCEDURE update_village_id_column();
9
  • 2
    BTW, this is a recursive trigger, you should avoid it.
    – McNets
    Commented Jul 18, 2020 at 16:07
  • Hi, I tagged the version I am currently using, and will add the error message soon. In what way is my code recursive? thank you.
    – PGerrits
    Commented Jul 18, 2020 at 21:48
  • Have a look at cascade/recursive triggers. The trigger is fired by itself.
    – McNets
    Commented Jul 19, 2020 at 11:50
  • update syntax appears wrong. Could you remove the "FROM schema_example.register_table" from the Pgplsql block and try.
    – Atty
    Commented Jul 19, 2020 at 15:43
  • @McNets Thank you, after checking what you said, I deleted the "OR UPDATE" part of the TRIGGER and that made the error to disappear. The trigger seems to be behaving as intended (although probably there might be cases this is limited in use). For now it seems it has solved.
    – PGerrits
    Commented Jul 20, 2020 at 18:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.