且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

外键约束 - 如何删除引用的记录?

更新时间:2023-01-20 11:33:36

您可以通过在 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.