Search code examples
mysqlsqldynamicddlbulk

MySQL: Get constraint name and drop it in one statement


I am getting constraint name from:

SELECT
  constraint_name
FROM
  information_schema.REFERENTIAL_CONSTRAINTS
WHERE
  constraint_schema = 'db' AND table_name = 'table';

then dropping it from the table. It works when done manually on local machine. Right now it is messing with my Jenkins build's db migration scripts.
Is there a way to do it in one statement?

Update
Following query gave me Access denied for user root@localhost

DELETE
FROM
  information_schema.REFERENTIAL_CONSTRAINTS
WHERE
  constraint_schema = 'db' AND table_name = 'table';

Solution

  • To auto-generate drop constraints to be run:

    SELECT concat('ALTER TABLE ', TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';') as theString
    FROM information_schema.key_column_usage 
    WHERE CONSTRAINT_SCHEMA = 'so_gibberish' 
    AND referenced_table_name IS NOT NULL;
    
    +---------------------------------------------------+
    | theString                                         |
    +---------------------------------------------------+
    | ALTER TABLE fc_junction DROP FOREIGN KEY fc_cat;  |
    | ALTER TABLE fc_junction DROP FOREIGN KEY fc_food; |
    +---------------------------------------------------+
    

    It auto-generates the strings to run. Massage the ordering if necessary. And off you go. Note that in Workbench/sqlyog you won't have the table bar output of course.