SQL Server 是否缓存查询结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15826784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:39:27  来源:igfitidea点击:

Does SQL Server CACHES Query Results?

sqlsql-servertsqlcachingsql-server-2008-r2

提问by pencilCake

When I run a query does the SQL Server caches the results?

当我运行查询时,SQL Server 会缓存结果吗?

Because: When I run the below query:

因为:当我运行以下查询时:

SELECT id
FROM Foo
WHERE Foo.Name LIKE '%bar%'

The query runs for 40 seconds on the 1st time.

查询在第一次运行40 秒

But on the second runit takes only a few seconds.

但是在第二次运行时它只需要几秒钟

Is this becausethe execution plan is somehow cached or actually the data is cached so that I can retrieve it much faster on the 2nd run?

这是因为执行计划以某种方式缓存了还是实际上数据被缓存了,以便我可以在第二次运行时更快地检索它?

回答by Filip De Vos

SQL Server does not cache the query results, but it caches the data pagesit reads in memory. The data from these pages is then used to produce the query result.

SQL Server 不会缓存查询结果,但会缓存它在内存中读取的数据页。然后使用来自这些页面的数据来生成查询结果。

You can easily see if the data was read from memory or from disk by setting

您可以通过设置轻松查看数据是从内存还是从磁盘读取

SET STATISTICS IO ON

Which returns the following information on execution of the query

它返回有关执行查询的以下信息

Table 'ProductCostHistory'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

The difference between logical and physical reads is the data read from memory.

逻辑读取和物理读取之间的区别在于从内存读取的数据。

SQL Server will also claim Memory for caching until the maximum (configured, or physical maximum) is reached and then the oldest pages are flushed.

SQL Server 还将要求内存用于缓存,直到达到最大值(配置或物理最大值),然后刷新最旧的页面。