如何删除表的所有外键

时间:2018-09-19 10:29:32

标签: mysql sql cursor procedure

我是编写程序的新手,我检查了一些stackoverflow帖子,但是没有找到删除特定表的所有外键的帖子。

我有一个书面的以下程序。

drop procedure if exists remove_foreign_key;

delimiter ;;

create procedure remove_foreign_key(vTableName varchar(128)) begin
if exists (select table_name from information_schema.columns where table_schema=database() and table_name = vTableName) then

(SELECT concat('ALTER TABLE ', TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';') 
FROM information_schema.key_column_usage 
WHERE table_schema=database() and TABLE_NAME = vTableName
AND referenced_table_name IS NOT NULL);

end if;
end if;
end;;

delimiter ;

call remove_foreign_key('my_table_name');

上面的查询返回我需要执行的所有查询(表包含的外键数量),但是我想一个一个地执行它们。我已经读过游标,但不确定其实现。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

下面是删除某些特定表的外键的mysql过程,希望对您有所帮助。您必须在call和booom中传递表名,然后删除这些表的外键。

DROP PROCEDURE IF EXISTS remove_foreign_key;
DELIMITER ;;
CREATE PROCEDURE remove_foreign_key(vTableName varchar(128))
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE cName VARCHAR(64);
  DECLARE cur CURSOR FOR
          SELECT DISTINCT CONSTRAINT_NAME
          FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
          WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME = vTableName
          AND REFERENCED_TABLE_NAME IS NOT NULL;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  SET AUTOCOMMIT=0;
  SET FOREIGN_KEY_CHECKS=0;

  OPEN cur;

  read_loop: LOOP
    FETCH cur INTO cName;
    IF done THEN
      LEAVE read_loop;
    END IF;
    SET @sql = CONCAT('ALTER TABLE ',vTableName,' DROP FOREIGN KEY ',cName,';');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  END LOOP;

  CLOSE cur;

  SET FOREIGN_KEY_CHECKS=1;
  COMMIT;
  SET AUTOCOMMIT=1;
END ;;

DELIMITER ;

call remove_foreign_key('table_name1');
call remove_foreign_key('table_name2');