Drop foreign key only if it exists

前端 未结 7 2066
清歌不尽
清歌不尽 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:38

    For greater re-usability, you would indeed want to use a stored procedure. Run this code once on your desired DB:

       DROP PROCEDURE IF EXISTS PROC_DROP_FOREIGN_KEY;
        DELIMITER $$
        CREATE PROCEDURE PROC_DROP_FOREIGN_KEY(IN tableName VARCHAR(64), IN constraintName VARCHAR(64))
        BEGIN
            IF EXISTS(
                SELECT * FROM information_schema.table_constraints
                WHERE 
                    table_schema    = DATABASE()     AND
                    table_name      = tableName      AND
                    constraint_name = constraintName AND
                    constraint_type = 'FOREIGN KEY')
            THEN
                SET @query = CONCAT('ALTER TABLE ', tableName, ' DROP FOREIGN KEY ', constraintName, ';');
                PREPARE stmt FROM @query; 
                EXECUTE stmt; 
                DEALLOCATE PREPARE stmt; 
            END IF; 
        END$$
        DELIMITER ;
    

    Thereafter, you can always replace this:

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

    with this:

    CALL PROC_DROP_FOREIGN_KEY('object', 'object_ibfk_1');
    

    Your script should then run smoothly whether object_ibfk_1 actually exists or not.

    A lot of credit due to: http://simpcode.blogspot.com.ng/2015/03/mysql-drop-foreign-key-if-exists.html

提交回复
热议问题