Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete all the triggers in a MySQL database using one SQL statement?

Tags:

mysql

triggers

I have a DB that I have cloned, and now all the logging triggers point to log tables in the original schema. I need to delete all of them in one go (there are several dozen) so that I can recreate them. How can this be done with one command?

like image 231
Matt Gibson Avatar asked Sep 28 '12 10:09

Matt Gibson


People also ask

How do I drop all triggers?

Execute this script: USE YourDBName GO SELECT ' GO ' + Char(10) + Char(13) + 'DROP TRIGGER ' + QUOTENAME(OBJECT_SCHEMA_NAME(O. [object_id])) + '. ' + QUOTENAME(name) FROM sys.

What SQL command is used to remove a trigger?

You can remove triggers using the Remove Physical File Trigger (RMVPFTRG) command, the SQL DROP TRIGGER statement, or System i® Navigator. Use the RMVPFTRG command to remove the association of a file and the trigger program.

How many triggers can be dropped in a single command SQL?

A single SQL statement can potentially fire up to four types of triggers: BEFORE row triggers. BEFORE statement triggers.

How do I delete an existing trigger in MySQL?

To destroy the trigger, use a DROP TRIGGER statement. You must specify the schema name if the trigger is not in the default schema: mysql> DROP TRIGGER test.


2 Answers

SELECT Concat('DROP TRIGGER ', Trigger_Name, ';') FROM  information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = 'your_schema'; 

Copy and paste the generated sql

like image 68
Lücks Avatar answered Oct 14 '22 02:10

Lücks


This is an old question, but since it's the one that keeps popping up in my searches I thought I'd post a solution here. In my case I needed to create a single file that had a full mysqldump, would then drop any triggers, and then re-add them all. I was able to do it by using the following command to append the DROP TRIGGER statements to my dump prior to appending the dump of the triggers.

mysql -u [db user] -p[db password] --skip-column-names [db name] -e 'SHOW TRIGGERS;' | cut -f1 | sed -r 's/(.*)/DROP TRIGGER IF EXISTS \1;/' >> dump.sql 

To actually drop all the triggers in the same command (as mentioned by @Stephen Crosby in the comments), you can just pipe this back into MySQL like so:

mysql -u [db user] -p[db password] --skip-column-names [db name] -e 'SHOW TRIGGERS;' | cut -f1 | sed -r 's/(.*)/DROP TRIGGER IF EXISTS \1;/' | mysql -u [db user] -p[db password] [db name] 
like image 45
Justin Warkentin Avatar answered Oct 14 '22 03:10

Justin Warkentin