How to verify if a Trigger exists or not before creating it?

Asked

Viewed 655 times

0

I intend to create a Trigger in table but first I would like to check if it already exists in my base .... how do I do ?

CREATE TRIGGER IF NOT EXISTS before_update_tableX ... ect

1 answer

5


Consulting the triggers

It depends on what you call "knowing if there is". Knowing if there is a name, or content?

For a "peek" just the

SHOW TRIGGERS

Now, if you need anything more elaborate:

SELECT
   trigger_schema,
   trigger_name,
   action_statement
FROM
   information_schema.triggers

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


By creating the Trigger

According to the manual

https://dev.mysql.com/doc/refman/5.7/en/create-trigger.html

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

Then it would just be a case of checking the return. If it failed, you will have the error code indicating the reason (and the code can determine if the fault was because the Trigger already exist).

Error 1359 - Trigger already exists

http://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html#error_er_trg_already_exists

If you just want to avoid an error return, you can do the opposite of what you asked for. Remove the Trigger existing, and create 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 Trigger old will be eliminated, and only worth the new.

  • I simply need to know if the name already exists ... !

  • @Andrépka the show triggers is enough then.

  • i have un script that create the Trigger x si o Trigger x exists does not create, if it does not exist then creates !

  • This was not asked, it was asked how to know if it exists before entering (and that’s what I answered). If you want to know how to create only if it doesn’t exist, that’s another question. I can even complement the answer, but remember to always ask, specify exactly what you want.

  • you’re right, I’ll do it next... !!

  • @Andrépka qq way, I will complement the answer Jajá

  • Thanks... but you can leave the old version of the answer there too!

  • @Andrépka left, and added. See if so resolves. I need to give an exit, but qq thing leave a comment I reviewed here later.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.