How to give parameter to Trigger function in PostgreSQL?

时间:2015-10-29 15:44:19

标签: sql postgresql

I have a table needitems as follow:

itemid   qty 
  5       10
  3       20

I wrote a trigger that on insert/update/delete it will copy the new record and save it in a table log : neededitems_log.

The thing is that I also need to know the productid. That information is avliable in the functions that did the insert/update/delete... however in the trigger I have no access to it. How can the function that did the insert/update/delete pass a variable to the trigger? if it can't be done what I can do?

with the above example...

assume that function X did update on itemid from qty 10 to qty 15 of productid 5555... I want the neededitems_log to show:

itemid   qty productid
  5       15   5555

1 个答案:

答案 0 :(得分:0)

您无法动态地将参数传递给触发器。任何清洁机制都是不可能的。几乎没有丑陋的方法 - 会话变量和其他方法,但我不能建议它。当您感觉到触发器的其他参数的必要性时,那么您的设计是错误的。所以不要这样做

当触发器很轻时触发器很好 - 触发器应该主要用于检查和审核。当您需要更复杂的工作时,您应该使用经典函数。函数的参数化更强,可维护性更好。太复杂的触发器是位陷阱,通常很大失败。

如果你真的需要它 - 那么会话变量比其他丑陋的解决方案错误更少:

postgres=# do $$
begin
  perform set_config('custom.var1', 10::text, true);
  raise notice 'session variable var1 = %', current_setting('custom.var1');
end;
$$;
NOTICE:  00000: session variable var1 = 1
DO