SQL Server中的执行计划什么时候生成?
在SQL Server的存储过程中,实际的SQL查询计划是什么时候生成的?当SQL第一次运行时或者存储过程编译时?与 Oracle 相比,您知道生成查询计划的成本有多高吗?
In a stored procedure in SQL Server, when is the actual SQL query plans generated? When the SQL is run for the first time or when the stored procedure is compiled? Any idea how expensive the generation of query plans is in comparison to Oracle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当查询运行时,SQL Server 将检查执行计划缓存中是否已存在该查询的执行计划。如果找到,它可以重用该执行计划。如果在缓存中找不到,它就会生成一个计划,放入缓存中以供后续调用重用,然后执行查询。所以它在执行查询时执行此操作。
计划在缓存中保留的时间取决于多种因素,包括:
- 该计划的使用频率
- 该计划提供多少“价值”
- 服务器上的内存压力
因此,如果给定查询的计划无法保留在缓存中,则在给定期间内可能会多次生成执行计划。此外,当 SQL Server 重新启动时,缓存也会被清除。
有一篇关于执行计划缓存和重用的很好的 MSDN 文章
When a query is run, SQL Server will check to see if an execution plan already exists for that query in the execution plan cache. If it finds one, it can reuse that execution plan. If it doesn't find one in the cache, it then generates a plan, puts in the cache ready for subsequent calls to reuse, and then executes the query. So it does this at the time when the query is executed.
How long a plan stays in the cache for is down to a number of factors, including:
- how often that plan is used
- how much "value" that plan offers
- memory pressure on the server
So a given query could have an execution plan generated multiple times over the course of a given period, if it's plan is not managing to stay in the cache. Also, when SQL Server restarts, the cache is cleared.
There's a good MSDN article on Execution Plan Caching and Reuse