我的情况的简化示例:我有一个像这样的脚本:
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秒?为什么?
请参见下面的结果屏幕截图。