删除所有表的触发器

时间:2019-05-29 09:13:09

标签: postgresql triggers

我有多个触发器,它们都是同一个触发器,但是位于不同的表上,例如

  tgname         |          trigger_table           
------------------------+----------------------------------
 updated_agg_trigger    | forecasts.forecast_1548180000
 updated_agg_trigger    | forecasts.forecast_1548187200
 updated_agg_trigger    | forecasts.forecast_1548162000
 updated_agg_trigger    | forecasts.forecast_1548190800
 updated_agg_trigger    | forecasts.forecast_1548183600
 updated_agg_trigger    | forecasts.forecast_1548172800
 updated_agg_trigger    | forecasts.forecast_1548111600
 updated_agg_trigger    | forecasts.forecast_1548136800
 updated_agg_trigger    | forecasts.forecast_1548129600

如何用一个命令删除所有表上的所有updated_agg_trigger触发器?

P.S。我不想删除所有触发器,仅删除updated_agg_trigger触发器。

1 个答案:

答案 0 :(得分:2)

运行动态语句遍历information_schema.triggers

DO $$
DECLARE
l_trig_name TEXT := 'updated_agg_trigger';
l_schema    TEXT := 'forecasts';
rec record;
BEGIN

for rec IN
(
  SELECT event_object_table as table_name
      ,trigger_schema as schema_name
      ,trigger_name
   FROM  information_schema.triggers
      WHERE  trigger_name   = l_trig_name
       AND trigger_schema   = l_schema
 ) 
   LOOP
        EXECUTE format ('DROP TRIGGER %I 
                ON %I.%I', rec.trigger_name,rec.schema_name,rec.table_name);
   END LOOP;

END $$;