如果stmt使用NoRows或Int? SQL

时间:2013-01-07 16:13:31

标签: sql sql-server sql-server-2008

我对最好的解决方法一无所知。目前的查询很好。问题是如果没有返回行,我希望if语句为true。我也不想两次编写查询,所以我如何以if语句为真并运行的方式编写它?

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

3 个答案:

答案 0 :(得分:3)

如果无法使用NULL AnInt,则可以将无匹配时的空子选择结果设为expectedInt

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

答案 1 :(得分:2)

喜欢这样吗?

DECLARE @Test INT

SELECT @Test = AnInt
FROM ATable
WHERE Cond

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

答案 2 :(得分:2)

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