JPReddy
JPReddy

Reputation: 65503

IF condition expression evaluation in TSQL

In programming language like C#, java if a condition has multiple expressions 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?

Upvotes: 3

Views: 17645

Answers (4)

Jeetendra singh negi
Jeetendra singh negi

Reputation: 19

    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

Upvotes: 0

Dane
Dane

Reputation: 9827

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

Upvotes: 1

pcofre
pcofre

Reputation: 4066

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

Upvotes: 0

MicSim
MicSim

Reputation: 26796

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.

Upvotes: 2

Related Questions