检查存储过程中的引用完整性
我在 sql server 2000 数据库中有一个 customer
表和一个 order
表。
我不希望 order
表中的订单的 customerID
不存在于 customer
表中,因此我将customerID
上的外键约束。
这一切都工作正常,但是当编写可能违反约束的存储过程时,有没有办法检查约束是否会被违反,如果会违反,则跳过/回滚查询?
目前所发生的一切是存储过程返回一个错误,该错误显示在我的 asp 页面上,并且看起来相当难看+大多数用户不会理解它。
如果可能的话,我想要一种更优雅的方式来处理错误。
谢谢
I have a customer
table and an order
table in an sql server 2000 database.
I don't want an order to be in the order
table with a customerID
that doesn't exist in the customer
table so I have put a foreign key constraint on customerID
.
This all works fine but when writing a stored procedure that could possibly violate the constraint, is there a way to check whether the constraint will be violated and, if it will be, skip/rollback the query?
At the minute all that happens is the stored procedure returns an error that is displayed on my asp page and looks rather ugly + most users wont understand it.
I would like a more elegant way of handling the error if possible.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有两个选择:
添加错误处理以捕获丑陋的内容,错误检查它以查看是否违反 FK 约束并将其显示给用户。恕我直言,这是更好的解决方案。
在存储过程中添加如下代码:
使用第二个选项,您将需要观察事务的一致性。例如,如果在您进行检查后删除客户,会发生什么情况。
You have two options:
Add error handling to catch the ugly, error inspect it to see if it's a FK constraint violation and display this to the user. This is IMHO the better solution.
Add code in the stored procedure like the following:
With the second option you will want to watch your transactional consistency. For example what happens if a customer is deleted after your check is made.
您可以在尝试操作之前检查数据,也可以尝试操作,然后在每个语句后检查错误,然后回滚等。
但是您可以完全在存储过程中处理它,并根据您的设计适当地返回给调用者。
看看这篇文章:http://www.sommarskog.se/error-handling- II.html
在 SQL Server 2005 中,可以使用 尝试/捕获
You can inspect the data before attempting the operation, or you can attempt the operation and then check the errors after each statement, then ROLLBACK etc.
But you can handle it entirely within stored procedures and return appropriately to the caller according to your design.
Have a look at this article: http://www.sommarskog.se/error-handling-II.html
In SQL Server 2005, there is a possibility of using TRY/CATCH