删除前检查 SQL 中是否存在完整性约束违规
我的问题有点类似于这个
我想检查是否DELETE 查询将因违反约束而失败。我想在数据库级别执行此操作,因为我认为让它失败并捕获错误是丑陋的。
另一种选择是使用 SELECT 查询“手动”检查它以查看是否存在约束,但恕我直言,这相当乏味。
有没有一种“本地”方法可以做到这一点?
My question is sort of similar to this one
I want to check if a DELETE query will fail because of a constraint violation. I'd like to do this on database level because I think letting it fail and catching the error is ugly.
Another option is "manually" checking for it using SELECT queries to see if there are constraints, but this is rather tedious, imho.
Is there a "native" way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单、最直接的方法是执行 DELETE,并捕获错误。
如果您对其他表运行 SELECT 语句,您可能会了解到行是否存在(暗示外键约束)。但外键约束只是多种完整性约束中的一种。
您还必须考虑一些完整性约束可能是通过触发器实现的(出于好的原因、坏的原因或根本没有原因)。
The simplest and most direct way is to execute the DELETE, and trap the error.
If you run a SELECT statement against other tables, you might learn whether rows exist (implying a foreign key constraint). But foreign key constraints are just one of many kinds of integrity constraints.
You also have to consider that some integrity constraints might be implemented with triggers (for good reasons, bad reasons, or no reasons at all).