gpt4 book ai didi

mysql - 如何删除表的所有外键

转载 作者:行者123 更新时间:2023-11-29 07:29:07 26 4
gpt4 key购买 nike

我是编写程序的新手,我查看了一些 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');

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

最佳答案

下面是删除某些特定表的外键的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');

关于mysql - 如何删除表的所有外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52403756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com