TSQL - 在插入之前如何根据不同列中的值检查值?
有没有办法实现 CHECK 约束来检查同一个表中不同列中的另一个值? 具体来说,我想确保在插入行之前要插入的“签出”日期值大于表中的“签入”日期值。
我可能会遗漏一些细节,所以如果是这种情况,请告诉我。
Is there a way to implement a CHECK constraint that checks a value against another value in a different column in the same table? Specifically, I want to ensure that a "checkout" date value to be inserted is greater than the "checkin" date value in the table before inserting the row.
I may be missing some details, so please let me know if this is the case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,MSSQL Server(和其他)允许检查表上的约束 - 以便您可以比较列:
Yes, MSSQL Server (and others) allow CHECK CONSTRAINTS on the table - so that you can compare columns:
您可以使用如下检查:
然后添加一个函数,如:
这些可能无法按编写的方式工作(抱歉,目前无法访问 SQL 引擎。)
或者您可能希望在查询中包含检查,以便您不需要当检查失败时,不必在代码中使用错误处理。
如果您只是希望插入失败,您可以将 where 子句扩展为如下所示:
如果您想返回某种类型的指示符,表明存在问题,您可以使用上面类似的内容,但添加 SELECT @@ROWCOUNT 或者您可以使用只需提前检查该值:
如果该值通过,@var 将等于 1。
You could use a check like:
Then add a function like:
Those may not work as written (sorry don't have access to an SQL engine at the moment.)
Or you may want to include the check in the query so that you don't have to use error handling in your code for when the check fails.
If you just want the insert to fail you could extend the where clause to be something like:
If you want to return some type of indicator that there was a problem you could either use something like above but add SELECT @@ROWCOUNT or you could use just check the value in advance:
@var would then be equal to 1 if the value passed.
您可以尝试使用触发器。
You can try to use triggers.