为什么在if语句中包装TSQL查询会显着增加运行时间?

以两种不同的方式运行相同的查询时,我的性能差异很大.从字面上来看,唯一的区别是它是否包含在if语句中.

这个查询实际上是一个较大的查询的一部分,但是我把它作为罪魁祸首.

运行查询本身返回几乎立即(返回0)

select COUNT(*) from Responses r where r.ResponseID not in (
    select ResponseID from data.GamingReport_Computerized
))

最终,我想避免基于该查询的结果运行复杂的计算,所以我将它包装在一个if语句,所以运行(〜10秒)需要更长的时间,我不知道为什么:

if (0 = (select COUNT(*) from Responses r where r.ResponseID not in (
    select ResponseID from data.GamingReport_Computerized
)))
begin select 'update will be skipped to save time' end
else begin select 'missing rows will be inserted' end

数据集不会改变,所以在这两种情况下,结果为零/’更新将被跳过’,而运行这两个版本的相同查询总是导致第一个版本快速完成,第二个版本占用10-12秒完成.

更新:这是查询执行计划的屏幕截图进行比较.他们为什么如此不同?对我来说非常意外

更新2:为了回应评论中的建议,我想提到以下查询与上述第二个版本相同,具有相同的执行计划,性能增加(即使用’exists’而不是比较count(* )到零没有区别).

if exists(select 1 from Responses r where r.ResponseID not in (
    select ResponseID from data.GamingReport_Computerized
))
begin select 'missing rows will be inserted' end
else begin select 'update will be skipped to save time' end

解决方法

我以前遇到过这个问题(很多次). 你可以检查你的索引是否是零碎的(如果需要的话可以对它们进行碎片整理),并且统计信息是最新的? 这可能对性能有相当大的影响,很可能是问题(因为寻求时间比扫描时间长).

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...