Apply a single trigger procedure to many different tables

元气小坏坏 提交于 2019-12-25 02:57:14

问题


In my PostgreSQL 9.1 database I have multiple tables and one trigger function.

Right now I am creating the trigger for each table by using that trigger function.

This methodology working fine. My boss has asked me to create the trigger commonly (only one time) by re-using that trigger function. That one trigger function should get used by all the tables in my database.


回答1:


You can find an example of creating a trigger with dynamic SQL using PL/PgSQL in the Audit Trigger sample for PostgreSQL. The same approach will work with any other DDL.

See the function audit.audit_table and use of format and EXECUTE there.

That said, needing to create tables procedurally can be (but isn't always) a sign of questionable schema design.

Simple example of dynamic SQL creating a table:

CREATE OR REPLACE FUNCTION demo_dynamic_table(tablename text) RETURNS void AS $$                                                                                      
BEGIN                                                                                                                                                                          
    EXECUTE format('CREATE TABLE %I (id serial primary key);', tablename);
END;
$$ LANGUAGE plpgsql;

The same approach works for trigger creation, etc.




回答2:


You can create PL/pgSQL procedure for table creation and move your trigger creation code inside it



来源:https://stackoverflow.com/questions/15567503/apply-a-single-trigger-procedure-to-many-different-tables

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