且构网

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

何时/为什么要在SQL Server中使用级联?

更新时间:2023-02-03 07:50:07

到目前为止我已经看到的总结:

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.

  • 你可能希望在允许操作级联之前,从用户那里获得更强大的确认,但这取决于您的应用程序。

  • 如果您设置外键,级联可能会让您陷入麻烦错误。但是,如果你这样做,你应该没关系。

  • 在你深入了解之前,先使用级联是不明智的。但是,这是一个有用的功能,因此值得花时间去理解。