Foreign key constraint - how to delete referenced record?(外键约束 - 如何删除引用的记录?)
问题描述
我偶然发现了一个非常基本的问题,因此没有真正考虑清楚.
我有两张桌子,比方说:
Table1: col1 PK,表 2:col1 FK 参考表 1(col1)当我想从 Table1 中删除记录时,该记录被 Table2 中的记录引用,SQL 会抛出错误,该 DELETE 语句冲突有约束.这是可以理解和期望的行为.
如果我真的想删除该行并在所有引用被删除键的行中将 Table2 中的引用设置为 NULL 怎么办?
我知道我可以手动完成 - 将 Table2 中的引用设置为 NULL 然后删除.但是有没有更简洁的方法?
您可以通过在 FK 关系上设置 Set Null 选项来配置插入和更新规范规则.我附上了一张来自 Sql Server Management Studio 的图片.此外,还有一篇有用的文章
I stumbled across a problem, which is very basic, thus didn't really think it through.
I have two tables, let's say:
Table1: col1 PK,
Table2: col1 FK references Table1(col1)
When I want to delete record from Table1, which is referenced by record in Table2, SQL would throw error, that DELETE statement coflicted with a constraint. Which is understandable and desired behaviour.
What if I really want to delete the row and set reference in Table2 to NULL in all rows referencing key being deleted?
I know that I can do it manually - set references in Table2 to NULL and then delete. But is there more concise way?
You could configure Insert and Update Specification rule by setting Set Null option on FK relationship. I have attached an image from Sql Server Management Studio. Also, there is a useful article here.
这篇关于外键约束 - 如何删除引用的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:外键约束 - 如何删除引用的记录?
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
