且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何短路 SQL Where 子句

更新时间:2023-10-23 14:37:16

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.