Create or replace trigger postgres

后端 未结 5 641
情话喂你
情话喂你 2021-02-02 05:01

I want to \"create or replace\" a trigger for a postgres table. However, there is not such sql expression.

I see that I can do a \"DROP TRIGGER IF EXISTS\"

相关标签:
5条回答
  • 2021-02-02 05:28

    Postgresql has transaction DDL so BEGIN > DROP > CREATE > COMMIT is the equivalent of CREATE OR REPLACE

    This is a nice write-up of how postgre's transactional DDL compares to other systems (such as oracle)

    Current postgres planned features regarding triggers do not include adding the REPLACE syntax.

    0 讨论(0)
  • 2021-02-02 05:30

    You should use two statements: one for drop trigger and another for creating a trigger.

    Example:

    DROP TRIGGER IF EXISTS my_trigger
      ON my_schema.my_table;
    CREATE TRIGGER my_trigger
      BEFORE INSERT OR UPDATE
      ON my_schema.my_table
      FOR EACH ROW EXECUTE PROCEDURE my_schema.my_function();
    
    0 讨论(0)
  • 2021-02-02 05:46

    you can use below code.

    DO $$ BEGIN
    
    CREATE (trigger, type , ...);
    
    EXCEPTION
      WHEN others THEN null;
    END $$;
    

    sample:

    DO $$ BEGIN
    
    CREATE TRIGGER trigger_workIDExist
      BEFORE INSERT OR UPDATE ON "GalleryModel"
      FOR EACH ROW EXECUTE PROCEDURE check_workIDExist();
    
    EXCEPTION
      WHEN others THEN null;
    END $$;
    
    0 讨论(0)
  • 2021-02-02 05:47

    No way to create or replace a trigger but can do this way

    DROP TRIGGER IF EXISTS yourtrigger_name on "yourschemaname"."yourtablename";
    
    0 讨论(0)
  • 2021-02-02 05:52

    You can combine CREATE OR REPLACE FUNCTION trigger_function with the following script in your SQL:

    DO $$
    BEGIN
      IF NOT EXISTS(SELECT *
        FROM information_schema.triggers
        WHERE event_object_table = 'table_name'
        AND trigger_name = 'trigger_name'
      )
      THEN
        CREATE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW EXECUTE PROCEDURE trigger_function();
      END IF;
    END;
    $$
    
    0 讨论(0)
提交回复
热议问题