将一个触发器过程应用于许多不同的表 [英] Apply a single trigger procedure to many different tables

查看:89
本文介绍了将一个触发器过程应用于许多不同的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的PostgreSQL 9.1数据库中,我有多个表和一个触发函数。

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.

推荐答案

您可以在审核触发器 PostgreSQL示例。

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.

请参见函数 audit.audit_table 和<$ c的使用。 $ c> format 和 EXECUTE

也就是说,需要创建表在程序上可以(但并非总是)是可疑的模式设计的标志。

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

动态SQL创建表的简单示例:

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.

这篇关于将一个触发器过程应用于许多不同的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆