Delete all foreign keys in database(MySql)

前端 未结 5 707
广开言路
广开言路 2020-12-15 18:04

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.

5条回答
  •  萌比男神i
    2020-12-15 18:28

    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 your FOREIGN KEYS will be gone.

    I leave the reverse (adding them back) as an exercise for you.

    SELECT CONCAT("alter table ", TABLE_NAME," drop foreign key ", CONSTRAINT_NAME,"; ") AS runMe
    FROM information_schema.key_column_usage 
    WHERE TABLE_SCHEMA='MY_SCHEMA_NAME' AND CONSTRAINT_NAME <> 'PRIMARY';
    

    If you need it to be schema independent, you can write: TABLE_SCHEMA=DATABASE() to get the current active DB name

提交回复
热议问题