Drop foreign key only if it exists

前端 未结 7 2075
清歌不尽
清歌不尽 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条回答
  •  长发绾君心
    2021-02-05 02:29

    Here is a workaround for the DROP FOREIGN KEY IF EXISTS, that is missing in MySQL and MariaDB versions before v10.1.4. You can also use it for every other statement you want, that should be depend on the existence of an FOREIGN KEY (e.g. for SELECT "info: foreign key exists." like in the example below).

    -- DROP FOREIGN KEY IF EXISTS
    SELECT
        COUNT(*)
    INTO
        @FOREIGN_KEY_my_foreign_key_ON_TABLE_my_table_EXISTS
    FROM
        `information_schema`.`table_constraints`
    WHERE
        `table_schema` = 'my_database'
        AND `table_name` = 'my_table'
        AND `constraint_name` = 'my_foreign_key'
        AND `constraint_type` = 'FOREIGN KEY'
    ;
    -- SELECT @FOREIGN_KEY_my_foreign_key_ON_TABLE_my_table_EXISTS;
    SET @statement := IF(
        @FOREIGN_KEY_my_foreign_key_ON_TABLE_my_table_EXISTS > 0,
        -- 'SELECT "info: foreign key exists."',
        'ALTER TABLE my_table DROP FOREIGN KEY my_foreign_key',
        'SELECT "info: foreign key does not exist."'
    );
    PREPARE statement FROM @statement;
    EXECUTE statement;
    

提交回复
热议问题