How do I only create a trigger if it does not exist?
When I do create or replace, I get a syntax error so I am looking for a way to test for the existence of a trigger.
I can always select * from pg_trigger, but I am sure there is a more suitable way.
Thanks
PL/pgSQL can be used to define trigger functions on data changes or database events. A trigger function is created with the CREATE FUNCTION command, declaring it as a function with no arguments and a return type of trigger (for data change triggers) or event_trigger (for database event triggers).
A trigger is a special type of stored procedure that automatically runs when an event occurs in the database server. DML triggers run when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.
A PostgreSQL trigger is a function called automatically whenever an event such as an insert, update, or deletion occurs. A PostgreSQL trigger can be defined to fire in the following cases: Before attempting any operation on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted).
Postgres can conditionally drop a trigger - see the docs. Do this before creating the trigger, then it will always work.
DROP TRIGGER IF EXISTS mytrigger ON mytable;
As Jack points out in the comments, this feature has only been available since 8.2; this has been out for more than four years though, so it should be available in your version.
CREATE TRIGGER (NameOfTrigger) AFTER INSERT OR UPDATE ON (NameOfTable)
DROP TRIGGER IF EXISTS (NameOfTrigger) ON (NameOfTable);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With