我偶然发现了一个非常基本的问题,因此没有真正考虑清楚.
我有两张桌子,比方说:
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.
这篇关于外键约束 - 如何删除引用的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将每个子标记转换为具有多个分隔符的单列-SQLConverting Every Child Tags in to a Single Column with multiple Delimiters -SQL Server (3)(将每个子标记转换为具有多个分隔符的单列-SQ
如何从多个表创建视图?How can I create a view from more than one table?(如何从多个表创建视图?)
根据前一行内的计算值创建计算值Create calculated value based on calculated value inside previous row(根据前一行内的计算值创建计算值)
如何将表格的前两列堆叠成一列,但也仅将第三How do I stack the first two columns of a table into a single column, but also pair third column with the first column only?(如何将表格的前两列堆
递归 t-sql 查询Recursive t-sql query(递归 t-sql 查询)
将月份名称转换为日期/月份编号(问题和答案的组Convert Month Name to Date / Month Number (Combinations of Questions amp; Answers)(将月份名称转换为日期/月份编号(问题和答案的组合