geogrow
geogrow

Reputation: 505

Trigger update another table

I have been trying to write a trigger function that updates the rows in the child table when the parent is changed for a while now. I have read Trigger procedure documentation but i have not really grasped how to build the functions.

This is what I have tried that does not work...

CREATE FUNCTION myschema.update_child() RETURNS trigger AS
$BODY$
BEGIN
UPDATE myschema.child 
set new.number = parent.number 
FROM myschema.parent
WHERE id = "id";
RETURN NEW;
END
$BODY$
LANGUAGE plpgsql

Then the trigger

CREATE TRIGGER update_child_after_update
   AFTER INSERT OR UPDATE OR DELETE
   ON myschema.child
   FOR EACH ROW
   EXECUTE PROCEDURE myschema.update_child();

Does anyone have some tips to give?
Best regards

Upvotes: 4

Views: 9400

Answers (1)

Tom-db
Tom-db

Reputation: 6878

You don't need to use the parent table in the body of the trigger function, because the values from the parent table are available in the function in the special variable OLD and NEW. In this case you only need NEW.

If you need the trigger only on update, than define a update-only trigger:

CREATE or replace FUNCTION update_child() RETURNS trigger AS
  $BODY$
BEGIN
  UPDATE child
  set number = NEW.number
  WHERE id = NEW.id;
  RETURN NEW;
END
$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER update_child_after_update
AFTER UPDATE 
ON parent
FOR EACH ROW
EXECUTE PROCEDURE update_child(); 

Upvotes: 13

Related Questions