DROP all foreign keys in MYSQL database

前端 未结 4 1528
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 01:33

Foreign keys are causing me too many problems modifying an database structure to meet new requirements - I want to modify primary keys but it seems I can\'t when foreign key

4条回答
  •  借酒劲吻你
    2020-12-24 02:12

    Another version of Zoozy code, here you can select only a table:

    SELECT concat('ALTER TABLE ', TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';') 
    FROM information_schema.key_column_usage 
    WHERE CONSTRAINT_SCHEMA = 'YOUR DB HERE' 
    AND TABLE_NAME='YOUR TABLE HERE' 
    AND REFERENCED_TABLE_NAME IS NOT NULL;
    

    Also with a procedure:

    DROP PROCEDURE IF EXISTS dropForeignKeysFromTable;
    
    delimiter ///
    create procedure dropForeignKeysFromTable(IN param_table_schema varchar(255), IN param_table_name varchar(255))
    begin
        declare done int default FALSE;
        declare dropCommand varchar(255);
        declare dropCur cursor for 
            select concat('alter table ',table_schema,'.',table_name,' DROP FOREIGN KEY ',constraint_name, ';') 
            from information_schema.table_constraints
            where constraint_type='FOREIGN KEY' 
                and table_name = param_table_name
                and table_schema = param_table_schema;
    
        declare continue handler for not found set done = true;
    
        open dropCur;
    
        read_loop: loop
            fetch dropCur into dropCommand;
            if done then
                leave read_loop;
            end if;
    
            set @sdropCommand = dropCommand;
    
            prepare dropClientUpdateKeyStmt from @sdropCommand;
    
            execute dropClientUpdateKeyStmt;
    
            deallocate prepare dropClientUpdateKeyStmt;
        end loop;
    
        close dropCur;
    end///
    

提交回复
热议问题