开发者

IF condition expression evaluation in TSQL

开发者 https://www.devze.com 2023-02-25 13:26 出处:网络
In programming language like C#, java if a condition has multiple expressio开发者_如何学Gons with AND(&&) operator then the second expression is only evaluated if first expression is true.

In programming language like C#, java if a condition has multiple expressio开发者_如何学Gons with AND(&&) operator then the second expression is only evaluated if first expression is true.

What about in TSQL? To be specific this is a condition in a Stored procedure in Microsoft Sql server.

IF (exprA AND exprB)

In the above condition if exprA is false then will the exprB is evaluated or not?


You can't rely on SQL Server not evaluating the second expression if the first one is false. See my answer to the question linked by Martin in his comment.


As others have noted, it depends on what your IF conditions are. However, if you are only using simple expressions, it will short circuit. Run the following and you'll see that the divide-by-zero error in the second expression never occurs:

IF (1 = 0 AND (1/0) = 0)
BEGIN
    PRINT 'test1'
END
ELSE
BEGIN
    PRINT 'test2'   
END


The CASE statement seems to allow short-circuiting as shown in the examples below:

-- Conditional Query
select case when  1>0 and 1/0>0 then 1 else 0 end

-- Short Circuited Conditional Query
select case when -1>0 and 1/0>0 then 1 else 0 end


    create proc ABCDemo1
    (
    @Name varchar(50),
    @date varchar(50)
    )
 as begin
    if(@Name!='' and @date='')
    begin
       select  * from Table1 where condition1
    end
    else if(@Name='' and @date!='')
    begin
       select * from Table2 where condition2
    end
    else if(@Name!='' and @date!='')
    begin
        select * from Table3 where condition3
    end
 end
0

精彩评论

暂无评论...
验证码 换一张
取 消