Drop foreign key only if it exists(仅当存在外键时才删除它)
问题描述
我在 MySQL 数据库中.
I'm on a MySQL database.
我正在这样做,但它不起作用.
I'm doing this, but it doesn't work.
ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;
我试图把这个 IF EXISTS 放在任何我能做的地方.如何在删除之前检查外键是否存在?
I've tried to put this IF EXISTS wherever I could. How can check if foreign key is exists before drop it?
推荐答案
如果你想删除外键(如果存在)并且不想使用过程你可以这样做(对于 MySQL) :
If you want to drop foreign key if it exists and do not want to use procedures you can do it this way (for MySQL) :
set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
CONSTRAINT_SCHEMA = DATABASE() AND
TABLE_NAME = 'table_name' AND
CONSTRAINT_NAME = 'fk_name' AND
CONSTRAINT_TYPE = 'FOREIGN KEY') = true,'ALTER TABLE table_name
drop foreign key fk_name','select 1');
prepare stmt from @var;
execute stmt;
deallocate prepare stmt;
如果有外键,我们将alter table语句放入变量中,如果没有,我们放入一个虚拟语句.然后我们执行它.
If there is foreign key we put alter table statement in variable and if there isn't we put a dummy statement. And then we execute it.
这篇关于仅当存在外键时才删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅当存在外键时才删除它
基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01