In mySQL 5, is there a way to drop all foreign key constraints on a table with one SQL statement without referring to them by name?
I'm writing a DB update script, and unfortunately some of the sites had constraints created with "wrong" names. I'm trying to avoid going in and getting the actual constraint names from the DB and inserting them back into SQL statements.
Here's a select that creates complete drop and create statements for all relations on a table. Not automatic in any way but easy enough to copy/paste from..
I used it to drop all relations, alter data types on the keys and then restore the relations with foreign key names á la MySQL Workbench. Might be helpful to someone..
I have a solution similar to Bing's answer, but it takes it one step further to be automatic and reusable in a procedure.
Since a prepared statement can only handle one statement at a time, the procedure loops through the foreign keys using a cursor and executes each drop one at a time.
To use the procedure on one of your tables just use the following, replacing table_schema and table_name with your values:
You can use this simple bash script:
Run:
and deleteForeignKeys.sh is
In your script you can always add SET FOREIGN_KEY_CHECKS=0 if you just want to get around the constraints.
Also, I have always deleted constraints on a per constraint basis using:
I don't think you can do all of them at once and I could not find any examples that show you can.
You can surely select * the table to a temp table, drop and recreate it, then copy back.