Trigger update another table

折月煮酒 提交于 2019-12-11 03:48:09

问题


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


回答1:


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(); 


来源:https://stackoverflow.com/questions/33034907/trigger-update-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!