2011-04-12 82 views
3

在像C#這樣的編程語言中,如果條件中有多個表達式和AND(& &)運算符,那麼只有在第一個表達式爲真時才計算第二個表達式。如果條件表達式評估在TSQL中

在TSQL中怎麼樣?具體來說,這是Microsoft Sql服務器中存儲過程的一個條件。

IF (exprA AND exprB) 

在上述情況下,如果exprA爲false,那麼exprB是否會被評估?

+5

「這取決於」。如果它包含'EXISTS'子查詢,那麼幾乎總是短路**不會發生。你永遠不能依靠它發生。您可以嵌套'CASE'表達式或嵌套'IF'表達式來保證它。 [我在此刻有類似問題的開放賞金](http://stackoverflow.com/questions/5542927/sql-server-conditional-flow/5543985#5543985)如果有人幻想看一些額外的案例! – 2011-04-12 14:21:37

回答

2

如果第一個表達式爲false,則不能依賴於SQL Server不評估第二個表達式。請參閱我對Martin在其評論中關聯的question的回答。

+0

我認爲你是對的,而不是依賴它,我應該使用嵌套的if或case。感謝您的信息。 – JPReddy 2011-04-13 05:13:30

0

CASE聲明似乎讓短路如下圖所示的例子:

-- 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 
1

正如其他人指出,這取決於你的IF條件是什麼。但是,如果您只使用簡單表達式,則會短路。運行以下,你會看到,除以零誤差的第二表達式永遠不會發生:

IF (1 = 0 AND (1/0) = 0) 
BEGIN 
    PRINT 'test1' 
END 
ELSE 
BEGIN 
    PRINT 'test2' 
END 
0
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