想象一下这个设置:
create table ObservationType
(
ObservationTypeId int primary key identity(1,1),
Name nvarchar(32) not null
)
create table Observation
(
ObservationId int primary key identity(1,1),
ObservationTypeId int foreign key references ObservationType(ObservationTypeId),
Title nvarchar(32) not null,
Description nvarchar(1024) not null,
StudentId int foreign key references Student(StudentId)
)
create table Student
(
foo bar
)
现在想象一下这里面充满了数据,它工作得很好。当用户想要删除某个观察类型时,你如何处理?您是否会自动删除具有该特定类型为 FK 的任何观察?
在现实世界中,您是如何处理这种情况的?
最佳答案
在许多情况下,这是正确的做法 - 这就是为什么 ON DELETE CASCADE
存在。
这意味着对于已删除的行,另一个表中定义为该行上的外键的任何行也将被删除。
你需要问的问题是这是否是用户真正想要的东西?在应用程序域内执行此类删除是否有意义?询问您的用户,如果他们删除观察类型,他们预计会发生什么 - 他们认为现有观察会发生什么。
有时,最好使用软删除(在状态字段中标记具有删除状态的行),以便您可以恢复/取消删除。这不是没有its share of problems .
关于sql-server - 如何处理删除可能是 FK 的数据库记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083650/