SQL 我应该使用 CASCADE DELETE 规则吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/278392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use the CASCADE DELETE rule?
提问by inspite
Duplicate of: When/Why to use Cascading in SQL Server?
I've always been too scared to use DELETE CASCADE, but as I get more confident (lazy :D), I'm thinking how bad can it be, is it best practise to use it or should I avoid it and clean up my foreign keys etc the old fashioned way (with stored procedures)?
我一直不敢使用 DELETE CASCADE,但随着我越来越自信(懒惰:D),我在想它有多糟糕,使用它是最佳实践还是我应该避免它并清理我的外键等老式方式(使用存储过程)?
回答by Tony Andrews
ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly you want to delete this order, which consists of a header and some lines. On the other hand, DELETE CUSTOMER should not delete the associated ORDERS because ORDERS are important in their own right, they are not just attributes of a customer.
ON DELETE CASCADE 很好,但只有当依赖行确实是被删除行的逻辑扩展时。例如,DELETE ORDERS 可以删除关联的 ORDER_LINES,因为您显然要删除此订单,它由一个标题和一些行组成。另一方面,DELETE CUSTOMER 不应删除关联的订单,因为订单本身很重要,它们不仅仅是客户的属性。
One way to think about this is: if I issue DELETE X and it also deletes Y, will I be happy or unhappy? And if I issue DELETE X and am told "cannot delete X because Y exists" will I be glad of the protection, or irritated at the inconvenience?
一种思考方式是:如果我发出 DELETE X 并且它也删除 Y,我会高兴还是不高兴?如果我发出 DELETE X 并被告知“由于 Y 存在而无法删除 X”,我会为这种保护感到高兴,还是会因不便而感到恼火?
回答by Galwegian
I prefer having control over exactly what is deleted (by explicitly declaring it), so I generally opt to delete via stored procedures, and not to use cascading deletes.
我更喜欢精确控制删除的内容(通过显式声明),所以我通常选择通过存储过程删除,而不是使用级联删除。