How to Short-Circuit SQL Where Clause

前端 未结 5 1636
自闭症患者
自闭症患者 2020-12-10 16:17

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

declare @queryWord as nvarchar(20) = \'asdas\'

SELECT  * FROM TABLE_1 
WHERE (ISDATE(@queryWord) =         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-10 16:36

    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.

    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)
    

    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.

提交回复
热议问题