本文介绍了何时/为什么要在SQL Server中使用级联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在SQL Server中设置外键时,您应该在什么情况下级联删除或更新,它背后的原因是什么?
When setting up foreign keys in SQL Server, under what circumstances should you have it cascade on delete or update, and what is the reasoning behind it?
适用于其他数据库。
我最喜欢看每个场景的具体示例,最好是从已经成功使用它们的人那里获取。
I'm looking most of all for concrete examples of each scenario, preferably from someone who has used them successfully.
推荐答案
到目前为止我已经看到的总结:
Summary of what I've seen so far:
- 级联删除可能当关系的语义可能涉及排他性是描述的一部分时,这是有意义的。例如,OrderLine记录是其父级订单的一部分,并且OrderLines将永远不会在多个订单之间共享。如果命令消失,则OrderLine也应该是一个没有命令的行将成为一个问题。
- Cascade Delete的典型例子是SomeObject和SomeObjectItems,对于项目记录来说,没有相应的主记录就没有任何意义。
- 如果您保留历史记录或使用软/逻辑删除,其中只将删除的位列设置为1 / true。
- Cascade Delete may make sense when the semantics of the relationship can involve an exclusive "is part of" description. For example, an OrderLine record is part of its parent order, and OrderLines will never be shared between multiple orders. If the Order were to vanish, the OrderLine should as well, and a line without an Order would be a problem.
- The canonical example for Cascade Delete is SomeObject and SomeObjectItems, where it doesn't make any sense for an items record to ever exist without a corresponding main record.
- You should not use Cascade Delete if you are preserving history or using a "soft/logical delete" where you only set a deleted bit column to 1/true.
- 级联更新当您使用真正的密钥而不是表的代理密钥(身份/自动增量列)时,这样做是有意义的。
- 级联更新的规范示例是当您有一个可变的外键,如可以更改的用户名。
- 您应该不使用带有身份/自动增量列的键级联更新。
- 级联更新最适用于结合独特的约束。
- Cascade Update may make sense when you use a real key rather than a surrogate key (identity/autoincrement column) across tables.
- The canonical example for Cascade Update is when you have a mutable foreign key, like a username that can be changed.
- You should not use Cascade Update with keys that are Identity/autoincrement columns.
- Cascade Update is best used in conjunction with a unique constraint.
- 你可能希望在允许操作级联之前,从用户那里获得更强大的确认,但这取决于您的应用程序。
- 如果您设置外键,级联可能会让您陷入麻烦错误。但是,如果你这样做,你应该没关系。
- 在你深入了解之前,先使用级联是不明智的。但是,这是一个有用的功能,因此值得花时间去理解。
这篇关于何时/为什么要在SQL Server中使用级联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!