Drop foreign key only if it exists

前端 未结 7 2163
清歌不尽
清歌不尽 2021-02-05 01:37

I\'m on a MySQL database.

I\'m doing this, but it doesn\'t work.

ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;

I\'ve

7条回答
  •  萌比男神i
    2021-02-05 02:36

    If you want to drop foreign key if it exists and do not want to use procedures you can do it this way (for MySQL) :

    set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
                CONSTRAINT_SCHEMA = DATABASE() AND
                TABLE_NAME        = 'table_name' AND
                CONSTRAINT_NAME   = 'fk_name' AND
                CONSTRAINT_TYPE   = 'FOREIGN KEY') = true,'ALTER TABLE table_name
                drop foreign key fk_name','select 1');
    
    prepare stmt from @var;
    execute stmt;
    deallocate prepare stmt;
    

    If there is foreign key we put alter table statement in variable and if there isn't we put a dummy statement. And then we execute it.

提交回复
热议问题