2013-01-07 21 views
-1

我對最好的解決方法毫無頭緒。當前查詢很好。問題是我想if語句爲true,如果沒有行返回。我也不想兩次寫這個查詢,所以我怎麼寫這個if語句是真的並且運行?如果用NoRows或Int命令? sql

IF (select AnInt from ATable where Cond) = expectedInt 
begin ... end 
+1

空子選擇的結果是你的子查詢保證返回不超過1個行? –

+0

@MartinSmith:是 – BruteCode

回答

3

如果NULLAnInt是不可能的,那麼你可以作出不匹配等於expectedInt

IF isnull((select AnInt from ATable where Cond), expectedInt) = expectedInt 
+0

好的一點是,該列不能爲空 –

2

像這樣?

DECLARE @Test INT 

SELECT @Test = AnInt 
FROM ATable 
WHERE Cond 

IF @Test IS NULL OR @Test = expectedInt 
BEGIN 
... 
END 
+0

+ 1 /接受我可以的時間 – BruteCode

+0

謝謝,但我認爲bummi的回答比我的效率更高 – MarkD

2
IF Coalesce((select TOP 1 AnInt from ATable where Cond),expectedInt) = expectedInt 
begin 
end 
+1

+1最好使用isnull,但由於coalesce會執行兩次查詢。 –