老外提问:

Hi, I have an sql query which takes 8 seconds in the first run. The next run there after takes 0.5 seconds and all consecutive runs take 0.5 seconds. Is the plan getting cached? How do i make this query run in 0.5 second in the first run itself? Please find the query below.

select isnull(joblabor.IDNumber,-1) 'ProcessTransactionID',EmpNo 'EmployeeID',case(joblabor.lJob) when '-1' then '0' else joblabor.ljob end 'JobID',
joblabor.ProcNo 'ActivityID',process.Process 'ActvityName', joblabor.shift 'Shift',case (isnull(suspend,0)) when 1 then 'true' else 'false' end 'Suspended',
joblabor.StartTime 'StartDateTime',joblabor.starttime 'StartTime', joblabor.updated 'UpdatedDate',
ProcQuant 'Quantity',Prochours 'Hours',isnull(Remarks,'') 'Remark',IsNull(JCNotes,'') 'Notes',IsNULL(JobFormSpecs.PartDes,'') as FormDesc,
IsNull(Job.EstDes1,'') 'JobDesc',0 'Standard',0 'MinimumStd',0 'MaximumStd',JobLabor.PartNo 'FormID',joblabor.CostDate 'CostDate',isnull(JobLabor.linenum,1) 'ProcessTransactionIndex',case(joblabor.suspend) when 1 then 1 else 0 end 'ProcessType'
,(joblabor.timepct*100) 'Percent',IsNull(Job.FCustNo,'') 'CustomerID', IsNull(Job.FCompany,'') 'CustomerName' , joblabor.EndTime 'EndDateTime',process.ProcGroup 'ActivityGroup',
case (LEN(LTRIM(SUBSTRING(Job.remark1, 1, 25)))) when 0 then 'false' else 'true' end 'HasJobNotes' ,
case (isnull(ProcessRemarks.ContainsProcessRemarks,0)) when 0 then 'false' else 'true' end 'HasProcessRemarks' ,
case (isnull(ChangeOrder.ContainsChangeOrders,0)) when 0 then 'false' else 'true' end 'HasAlteration'
,isnull(joblabor.costcode,'') 'CostStatus'
,isnull(Complete,'') 'CompletionCode',GRYield 'GrossYield',NetYield 'NetYield'
from BBJobCST joblabor (nolock)
Left Outer Join bbjthead Job (nolock) on (joblabor.lJob = Job.lJob)
inner join SSProces as Process (nolock) on( process.ProcNo = joblabor.ProcNo AND process.archive = 0)
left outer join bbPthead JobFormSpecs (nolock) on (ltrim(rtrim(joblabor.Ljob)) = ltrim(rtrim(JobFormSpecs.LJob)) and ltrim(rtrim(JobLabor.PartNo))=ltrim(rtrim(jobFormSpecs.PartNo)) )
left outer join (
SELECT Count(bbchghdr.ljob) 'ContainsChangeOrders', bbchghdr.ljob FROM bbchghdr (nolock)
inner join bbchglin (nolock) ON bbchghdr.ljob = bbchglin.ljob AND bbchghdr.changeno = bbchglin.changeno
WHERE type = 'P' AND descript NOT LIKE '' group by bbchghdr.ljob) ChangeOrder on ChangeOrder.ljob=joblabor.ljob
left join (
SELECT Count(bbjobcst.ljob) 'ContainsProcessRemarks', bbjobcst.ljob
FROM bbjobcst (nolock) WHERE ( LEN(LTRIM(SUBSTRING(bbjobcst.jcnotes, 1, 25))) > 0 or LEN(LTRIM(remarks)) > 0)
Group By bbjobcst.ljob) ProcessRemarks on ProcessRemarks.ljob=joblabor.ljob
where joblabor.empno = '000002013' and
(isnull(joblabor.endtime,'') = '' or suspend=1 ) and (joblabor.ProcHours = 0 or suspend=1 )
and joblabor.ljob <> 0
order by joblabor.Costdate desc,joblabor.starttime desc,[linenum] asc

Thanks in advance.

回答:

It isn’t the query plan that is getting cached – it is the actual data and indexes which are being cached.  This is common behavior of any database. If you ran the query, then waited a while and ran again (keeping the session active), you would see the query take longer again, based on the cached data/indexes being flushed to make room for other data.

You can see if you can reduce the 0.5 seconds repeat time, and/or you can see if you can reduce the intermediate result sets (which are usually what get cached and speed up the queries the second..nth runs).

If the query is producing a large intermediate result set (perhaps a large join where most records are then discarded), you may be able to speed it up by changing parts of your query.  Also, sometimes just adding the right index can solve issues like this.

Look at the execution plan and see if there are any “table access full”, “index access full”, “cartesian”, or similar joins indicating inefficient join/indexing.

意思就是说Sql语句第一次查询慢的原因不仅仅是因为执行计划没有被缓存这么简单,有时候你会发现Sql语句重用了执行计划,但是第一次查询还是很慢。就如同上面回答一样,最主要的原因是第一次查询的时候,Sql Server会将查询出的部分数据和索引从磁盘加载到内存作为缓存,而第二次查询的时候就直接从内存缓存中拿出数据了,自然要比从磁盘上加载数据快很多,Sql Server会定期清除缓存,所以一段Sql语句如果长期不执行后,就需要从磁盘从新加载数据。

原文链接

转载于:https://www.cnblogs.com/OpenCoder/p/7147292.html

为什么Sql Server的查询有时候第一次执行很慢,第二次,第三次执行就变快了相关推荐

  1. 剖析SQL Server 2005查询通知之基础篇

    剖析SQL Server 2005查询通知之基础篇 注:这是本人转载的文章. 摘要 在本系列文章中,我们将深入探讨如何把.NET 2.0和SQL Server 2005的查询通知特征联合起来,以便通知 ...

  2. SQL Server 2016 查询存储性能优化小结

    SQL Server 2016已经发布了有半年多,相信还有很多小伙伴还没有开始使用,今天我们来谈谈SQL Server 2016 查询存储性能优化,希望大家能够喜欢 作为一个DBA,排除SQL Ser ...

  3. 优化SQL Server数据库查询方法

    本文详细介绍了优化SQL Server数据库查询方法. SQL Server数据库查询速度慢的原因有很多,常见的有以下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) ...

  4. SQL Server 2000查询n到m条记录

    SQL Server 2000查询n到m条记录? (1)select top m * from tablename where id not in (select top n id from tabl ...

  5. SQL Server 2005查询处理结构-用户模式计划(UMS)

    SQL Server 2005查询处理结构-用户模式计划(UMS) 在对数据库进行性能调优时,必须全面的考虑各种可能造成系统性能瓶颈的各种因素,因此深入了解SQL Server 2005的查询处理机构 ...

  6. SQL server management 查询所有触发器

    SQL server management 查询所有触发器 SQL server management 查询所有触发器 SELECT OBJECT_NAME(a.parent_obj) AS [表名] ...

  7. Sql Server参数化查询之where in和like实现之xml和DataTable传参

    在上一篇Sql Server参数化查询之where in和like实现详解中介绍了在Sql Server使用参数化查询where in的几种实现方案,遗漏了xml和表值参数,这里做一个补充 文章导读 ...

  8. [转]Sql Server参数化查询之where in和like实现详解

    本文转自;http://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.html 文章导读 拼SQL实现where in查询 使用CHARIND ...

  9. SQL Server FILESTREAM查询和文件组

    In this series of the SQL Server FILESTREAM (see TOC at bottom), We have gone through various aspect ...

  10. 数据库-SQL Server数据库查询速度慢(连接超时)原因及优化方法

    SQL Server数据库查询速度慢的原因有很多,常见的有以下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列 ...

最新文章

  1. python爬虫requestsget_精讲Python中的requests方法
  2. 2432功率计使用说明_为什么说功率计是自行车开挂神器?
  3. vim实用技巧-笔记(第九章)
  4. 世界顶级精英们的人生哲学 【转】
  5. docker 安装 nacos/nacos-server 镜像并配置本地数据库
  6. 农民约翰是一个惊人的会计_我的朋友约翰在CSS Grid中犯了一个错误。 不要像约翰-这样做。
  7. .NET Core开发的iNeuOS物联网平台部署树莓派(raspbian),从网关到云端整体解决方案。助力2019中国.NET峰会。
  8. 【限时免费】真实数据操练,经典算法分析,实战NLP领域,只等你来!
  9. MS2108 USB 数字视频采集芯片 支持8bit/16bit BT601/BT709/BT656/ BT1120转USB
  10. 双网络打印机虚拟服务器,在VMware Workstation 7虚拟机中使用主机打印机
  11. AUTOCAD--动态缩放
  12. 电容击穿之后是开路还是短路?
  13. cesium polygon添加边界线不起作用
  14. 我94年的,做了一年外包我就跑路了
  15. 5g的八大关键指标_【一起学5G】_5G NR关键性能KPI指标
  16. 贴吧猫头鹰隐藏二维码是怎么制作的?
  17. webstorm 插件拓展(一)
  18. 打算的亲爱额请问请问额
  19. 晶圆在低温探针台中的安装方式——Cyanoacrylate粘合剂
  20. replace 与 replaceAll

热门文章

  1. 【Solidity】7. 部件 - 深入理解Solidity
  2. Cocos 环境搭建 流程~~~~~
  3. 计算机安全群,大开眼界||斯坦福大学信息安全课程群
  4. 纳德拉:没有Excel的世界是无法想象的
  5. [计算机毕业设计]数字水印算法
  6. 详解3D结构光如何标定
  7. 无中介租房搜房工具 V1.0
  8. 线性规划中的对偶(Duality in linear programs)
  9. 物理定律告诉你:表白可能巨亏,分手一定血赚
  10. cesium鼠标控制键盘_Package - cesium-plotting-symbol