如何短路 SQL Where 子句

编程入门 行业动态 更新时间:2024-10-24 23:15:40
本文介绍了如何短路 SQL Where 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 SQL 服务器中执行以下查询:

I am trying to perform the following query in SQL server:

declare @queryWord as nvarchar(20) = 'asdas' SELECT * FROM TABLE_1 WHERE (ISDATE(@queryWord) = 1) AND TABLE_1.INIT_DATE = CONVERT(Date, @queryWord)

这显然会导致错误,因为 'asdas' 无法转换为 Date.虽然,我期待不同的行为.也就是说,因为 ISDATE(@queryWord) = 1 是假的,我希望 SQL 不检查第二个条件,但显然,它确实如此.

This obviously causes an error because 'asdas' cannot be converted to Date. Although, I was expecting a different behavior. That is, because ISDATE(@queryWord) = 1 is false, I was expecting SQL to do not check the second condition, but apparently, it does.

我知道还有其他一些方法可以执行此查询,但这不是我的问题.不知道有没有什么办法不检查第二个条件是不是第一个不满足.我很好奇,因为我认为 SQL 已经做到了.

I know there are some other ways to perform this query but this is not my question. I wonder if there is some way to do not check the second condition is the first one does not satisfy. I am curious because I thought that SQL already did this.

推荐答案

SQL Server 不执行短路(也不应该).

SQL Server does not do short-circuiting (nor should it).

如果您需要它在某些情况下不尝试某事,您需要以编写查询的方式强制这样做.

If you need it to not try something under some circumstances, you need to force that in the way that you write your query.

对于此查询,最简单的解决方法是在 WHERE 子句中使用 CASE 表达式.

For this query the easiest fix would be to use a CASE expression in your WHERE clause.

declare @queryWord as nvarchar(20) = 'asdas' SELECT * FROM TABLE_1 WHERE TABLE_1.INIT_DATE = (CASE WHEN ISDATE(@queryWord) = 1 THEN CONVERT(Date, @queryWord) ELSE NULL END)

副手,CASE 和查询嵌套是我能想到的唯一两种受支持的方法,可以强制对 SQL 中的依赖条件进行求值顺序.

Off-hand, CASE and query-nesting are the only two supported ways that I can think of to force an order of evaluation for dependent conditions in SQL.

更多推荐

如何短路 SQL Where 子句

本文发布于:2023-10-22 08:24:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!