I would like to rename a column in a table that is a foreign key to many tables. Apparently this is only possible if you delete the constraints, as I found out in this link.
I dont want to delete all the constratints manually is there a way to delete all the foreign key constraints in the database?
I have also tried SET FOREIGN_KEY_CHECKS=0;
but I still cant rename the column.
You Can Try using As Like of Following ..
Also you can try with Reference Key.As like .....
You can use this SQL to generate ALTER TABLES (
!!YOUR_SCHEMA_HERE!!
needs to be replaced by your schema):It will generate SQL like this:
Executing the following query
will show you all the constraints (with the column name, constraint type, table and schema) that exist in your database. You'll notice these columns:
Then, if you're planning to delete each constraint you have referencing your column, you should consider the REFERENCED_* columns and run something like:
http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html
The following query will build the correct syntax automatically. Make sure you put your real DB schema name in the
WHERE
condition. Just execute each line returned and all yourFOREIGN KEYS
will be gone.I leave the reverse (adding them back) as an exercise for you.
If you need it to be schema independent, you can write:
TABLE_SCHEMA=DATABASE()
to get the current active DB nameI was still having some issues after finding this thread, but I have seemed to find a workflow that works for me.
Database Deletion
If you are using MySQL Workbench, you will need to turn SAFE UPDATE off by doing the following 3 steps:
Steps to start purge database and start new
(This MySQL script will create a DELETE FROM script for each table in your database.)
SELECT concat('DELETE FROM ',table_schema,'.',table_name,';') FROM information_schema.table_constraints WHERE table_schema='!!TABLE_SCHEMA!!';
Copy the output of this and run it. You might need this line-by-line.
(This MySql script will create na ALTER TABLE _ DROP FOREIGN KEY script for each table in your database.)
SELECT concat('alter table ',table_schema,'.',table_name,' DROP FOREIGN KEY ',constraint_name,';') FROM information_schema.table_constraints WHERE constraint_type='FOREIGN KEY' AND table_schema='!!TABLE_SCHEMA!!';
Copy the output of this and run it. You might need this line-by-line.
After you've done this, you SHOULD be able to run your DROP DATABASE script.