如果stmt带有NoRows或Int?sql

如果stmt带有NoRows或Int?sql,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我不知道最好的办法是什么。当前查询很好。问题是如果没有返回任何行,我希望if语句为true。我也不想写两次查询,那么我该如何写才能使if语句为true并运行呢 IF (select AnInt from ATable where Cond) = expectedInt begin ... end 像这样 DECLARE @Test INT SELECT @Test = AnInt FROM ATable WHERE Cond IF @Test IS NULL OR @Test = expe

我不知道最好的办法是什么。当前查询很好。问题是如果没有返回任何行,我希望if语句为true。我也不想写两次查询,那么我该如何写才能使if语句为true并运行呢

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

DECLARE @Test INT

SELECT @Test = AnInt
FROM ATable
WHERE Cond

IF @Test IS NULL OR @Test = expectedInt
BEGIN
...
END
如果NULL AnInt不可能,则可以使not匹配的NULL子选择结果等于EXPECTED AnInt


您的子查询是否保证返回不超过1行?+1最好使用isnull,因为coalesce将执行两次查询。谢谢,但我认为bummi的答案比我的更有效
IF Coalesce((select TOP 1 AnInt from ATable where Cond),expectedInt) = expectedInt
begin
end
IF isnull((select AnInt from ATable where Cond), expectedInt) = expectedInt