我有一个触发器,但我需要关联我postgres的所有表.
下面有这样的命令吗?
下面有这样的命令吗?
CREATE TRIGGER delete_data_alldb BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data();
好吧,没有数据库范围的触发器创建,但对于所有这样的批量管理操作,您可以使用Postgresql系统表为您生成查询,而不是手动编写它们.
在这种情况下,您可以运行:
原文链接:https://www.f2er.com/postgresql/192051.html在这种情况下,您可以运行:
SELECT 'CREATE TRIGGER ' || tab_name || ' BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data();' AS trigger_creation_query FROM ( SELECT quote_ident(table_schema) || '.' || quote_ident(table_name) as tab_name FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog','information_schema') AND table_schema NOT LIKE 'pg_toast%' ) tablist;
这将为您提供一组sql命令,如:
CREATE TRIGGER schema1.table1 BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data(); CREATE TRIGGER schema1.table2 BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data(); CREATE TRIGGER schema1.table3 BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data(); CREATE TRIGGER schema2.table1 BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data(); CREATE TRIGGER schema2."TABLE2" BEFORE DELETE ON ALL DATABASE FOR EACH ROW EXECUTE PROCEDURE delete_data(); ... etc
您只需要立即运行它们(通过psql或pgAdmin).
现在一些解释:
>我使用information_schema.tables系统表选择数据库中的表名.因为存在几乎所有表的数据,所以请记住从select中排除pg_catalog和information_schema模式以及toast表.>我使用quote_ident(text)函数,如果需要,将字符串放在双引号(“”)内(即带空格或大写字母的名称要求).>当我有表名列表时,我只是将它们与一些静态字符串连接起来以获取我的sql命令.>我使用子查询编写该命令,因为我希望您能更好地了解这里发生了什么.您可以通过放置quote_ident(table_schema)||来编写单个查询” || quote_ident(table_name)代替tab_name.