简体   繁体   English

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

[英]How to delete a foreign key from MySQL table dynamically?

I am trying to drop a foreign key from a table referencing a specified table. 我试图从引用指定表的表中删除外键。 I don't know the name of the foreign key, I only know the table it is in and the table it references. 我不知道外键的名称,我只知道它所在的表和它引用的表。 This is what I got so far: 这是我到目前为止所得到的:

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);

But I get an error: 但是我收到一个错误:

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

The select alone works: 单独的选择工作:

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)

I don't believe you can do that. 我不相信你能做到这一点。 The alter statement doesn't know how to extrapolate the results from your select into multiple executions of drop foreign key. alter语句不知道如何将select中的结果外推到drop外键的多次执行中。

I usually do something like this: 我通常做这样的事情:

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';

I execute the above query which will build all the alter statements for me. 我执行上面的查询,它将为我构建所有的alter语句。 I then take that list of alter statements and run them manually. 然后我获取alter语句列表并手动运行它们。

I don't have mySQL to hand so can't test this, but I think something along the lines of the following will work: 我没有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

My experience of MySQL is limited so this is a mixture of your answer and information from the MySQL Website 我对MySQL的体验是有限的,所以这是你的答案和MySQL网站信息的混合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM