SQL Server-跳过了“ false” IF语句,但仍需要通常的时间吗?

时间:2019-10-30 14:06:55

标签: sql sql-server sql-server-2017

我的情况的简化示例:我有一个像这样的脚本:

DECLARE @var1 int = 1
DECLARE @var2 int = 2

IF (@var1 = 1)
   BEGIN
      -- Small SELECT statement that uses @var2
      -- Usually takes less than a second to complete
   END
ELSE
   BEGIN
      -- Large SELECT statement that uses @var2
      -- Usually takes roughly 8 seconds to complete
   END

我遇到的问题是:

如果@var1 = 1,并且@var2 =(所有),则脚本将在不到一秒钟的时间内运行。

但是,如果在保持@var2 = 1的情况下更改@var1的值,即使没有输入ELSE子句,运行时间也会突然跳到8秒。

例如,如果我依次执行以下操作,则结果如下:

1) @var1 = 1, @var2 = 2 -- Less than a second
2) @var1 = 1, @var2 = 3 -- 8 seconds even though ELSE clause isn't entered?
3) @var1 = 1, @var2 = 3 -- Less than a second

尽管实际上SELECT子句中的ELSE语句实际上未返回任何内容,但似乎似乎正在重新评估它。这是SQL Server中的预期行为吗?

(请注意,如果我完全注释掉ELSE子句,则脚本总是在不到一秒钟的时间内完成。)

我试图解决以下问题:

DECLARE @var1 int = 1
DECLARE @var2 int = 2

DECLARE @time1 datetime = GETDATE()

IF (@var1 = 1)
   BEGIN
      -- Small SELECT statement that uses @var2
      -- Usually takes less than a second to complete
   END

DECLARE @time2 datetime = GETDATE()

IF (@var1 <> 1)
   BEGIN
      -- Large SELECT statement that uses @var2
      -- Usually takes roughly 8 seconds to complete
   END

DECLARE @time3 datetime = GETDATE()

SELECT @time1 [Time 1], @time2 [Time 2], @time3 [Time 3]

按预期,@time2等于@time3,因为从未输入ELSE子句,但是脚本的运行时间仍然是8秒?为什么?

请参见下面的结果屏幕截图。

enter image description here

0 个答案:

没有答案