首页 > 解决方案 > postgres trigger pass input to function

问题描述

I am trying to make a trigger that when a value is put into table1 it is then copied into table2. I have the following function which works correctly:

Create function func1(a integer) returns void
Language SQL as $$
insert into table2 values (a);$$;

and here is the trigger (it doesn't work):

Create trigger trig1
Before update on table1
For each row
Execute function func1(old.attr1)

I am trying to follow this documentation. Here is the part in particular I am following:

CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE PROCEDURE log_account_update();

I figured that old.attribute gives a particular attribute of the old row before it is changed. If I'm wrong on this let me know. Thanks

标签: postgresql

解决方案


文档说明了触发器中调用的函数:

用户提供的函数,声明为不带参数并返回类型触发器,当触发器触发时执行。

此函数可以访问OLDNEW对象。您可以修改现有功能:

Create function func1()  RETURNS trigger
as $$
 BEGIN
   insert into table2 values (OLD.attr1);   
   RETURN NEW; 
 END;
$$  LANGUAGE plpgsql;

Create trigger trig1
  Before update on table1
  For each row
  Execute function func1();

推荐阅读