【问题标题】:How to delete a foreign key from MySQL table dynamically?如何从 MySQL 表中动态删除外键?
【发布时间】:2012-02-28 14:14:46
【问题描述】:

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

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)

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我不相信你能做到。 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 语句。然后,我获取更改语句的列表并手动运行它们。

    【讨论】:

      【解决方案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 的信息的混合体

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-22
        • 1970-01-01
        • 1970-01-01
        • 2017-03-06
        • 2012-02-28
        • 1970-01-01
        • 2015-06-16
        • 1970-01-01
        相关资源
        最近更新 更多