How to check if a trigger exists or not before creating it?

0

I want to create a trigger in table_X but first I would like to check if it already exists on my base .... how do I?

CREATE TRIGGER IF NOT EXISTS before_update_tableX ... ect

    
asked by anonymous 16.12.2016 / 17:02

1 answer

5

Consulting the triggers

It depends on what you call "knowing if it exists". Know if the name, or content exists?

For a "peek" just the

SHOW TRIGGERS

Now, if you need something more elaborate:

SELECT
   trigger_schema,
   trigger_name,
   action_statement
FROM
   information_schema.triggers

-- aqui vc cria sua condicao se quiser --
WHERE
   trigger_name = "batatas"


When creating trigger

According to the manual

  

link

There is no specific way to condition creation into existence or not, but there is no risk of creating two triggers with the same name, you will simply get an error return when trying.

That would be just the case of checking the return. If it failed, it will have the error code indicating the reason (and the code can determine if the failure was because the trigger already exists).

  

Error 1359 - The trigger already exists

     

link

If you just want to avoid a return error, you can do the opposite of what you asked for. Remove the existing trigger , and create it again:

DROP TRIGGER IF EXISTS tres_pratos_de_trigo;

DELIMITER $
CREATE TRIGGER tres_pratos_de_trigo
... etc ...

But attention , in this case is the opposite of what was requested. The old trigger will be deleted, and will only be worth the new one.

    
16.12.2016 / 17:07