在像C#這樣的編程語言中,如果條件中有多個表達式和AND(& &)運算符,那麼只有在第一個表達式爲真時才計算第二個表達式。如果條件表達式評估在TSQL中
在TSQL中怎麼樣?具體來說,這是Microsoft Sql服務器中存儲過程的一個條件。
IF (exprA AND exprB)
在上述情況下,如果exprA爲false,那麼exprB是否會被評估?
在像C#這樣的編程語言中,如果條件中有多個表達式和AND(& &)運算符,那麼只有在第一個表達式爲真時才計算第二個表達式。如果條件表達式評估在TSQL中
在TSQL中怎麼樣?具體來說,這是Microsoft Sql服務器中存儲過程的一個條件。
IF (exprA AND exprB)
在上述情況下,如果exprA爲false,那麼exprB是否會被評估?
的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
正如其他人指出,這取決於你的IF條件是什麼。但是,如果您只使用簡單表達式,則會短路。運行以下,你會看到,除以零誤差的第二表達式永遠不會發生:
IF (1 = 0 AND (1/0) = 0)
BEGIN
PRINT 'test1'
END
ELSE
BEGIN
PRINT 'test2'
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
「這取決於」。如果它包含'EXISTS'子查詢,那麼幾乎總是短路**不會發生。你永遠不能依靠它發生。您可以嵌套'CASE'表達式或嵌套'IF'表達式來保證它。 [我在此刻有類似問題的開放賞金](http://stackoverflow.com/questions/5542927/sql-server-conditional-flow/5543985#5543985)如果有人幻想看一些額外的案例! – 2011-04-12 14:21:37