如何动态删除MySQL表中的外键?

时间:2012-02-28 14:14:46

标签: mysql sql

我试图从引用指定表的表中删除外键。我不知道外键的名称,我只知道它所在的表和它引用的表。这是我到目前为止所得到的:

alter table tblTableWhereFKIs drop foreign key (select constraint_name 
from information_schema.key_column_usage 
where referenced_table_name = 'tblReferencedByFK' and table_name = 'tblTableWhereFKIs' limit 1);

但是我收到了一个错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(select constraint_name
from information_schema.key_column_usage
where referen' at line 1

单独选择有效:

mysql> select constraint_name
    -> from information_schema.key_column_usage
    -> where referenced_table_name = 'tblReferencedByFK' and table_name = 'tblTableWhereFKIs' limit 1;
+-----------------------------------------+
| constraint_name                         |
+-----------------------------------------+
| fk_tblTableWhereFKIs_tblReferencedByFK1 |
+-----------------------------------------+
1 row in set (0.08 sec)

2 个答案:

答案 0 :(得分:2)

我不相信你能做到这一点。 alter语句不知道如何将select中的结果外推到drop foreign key的多次执行中。

我通常做这样的事情:

SELECT CONCAT('alter table ', table_name, ' drop foreign key ', constraint_name, ';')
FROM information_schema.key_column_usage
WHERE referenced_table_name = 'tblReferencedByFK' and table_name = 'tblTableWhereFKIs';

我执行上面的查询,它将为我构建所有的alter语句。然后我获取alter语句列表并手动运行它们。

答案 1 :(得分:2)

我手边没有mySQL,所以无法测试,但我认为以下内容可行:

DECLARE @SQL VARCHAR(100)

SELECT  @SQL = 'alter table tblTableWhereFKIs drop foreign key ' + constraint_name
FROM    information_schema.key_column_usage
WHERE   referenced_table_name = 'tblReferencedByFK' 
AND     table_name = 'tblTableWhereFKIs'

PREPARE stmt FROM @SQL
EXECUTE stmt

我对MySQL的体验有限,所以这是你的答案和MySQL Website

的信息的混合体。