在 SQL Server 2012 中重用查询计划

Reusing query plan in SQL Server 2012

我正在使用 SQL 服务器,我想从重用查询计划中获益。我找到了这个 document,但我仍然不清楚我的查询计划是否被重用。

declare @su dbo.IntCollection      -- TABLE (Value int not null)

insert into @su values (1),(2),(3) --... about 500 values

update mt
set mt.MyField = getutcdate()
from MyTable mt
join @su vsu on mt.Id = vsu.Value -- Clustered PK, int

从技术上讲,批处理的文本不同于 运行 运行,因为在 @su 中插入了不同的值。但更新查询的文本保持不变。如果我使用的是 .NET,我基本上会将 table 变量传递给 SQL 命令,但我使用的是 Python 并且看起来无法传递 table 参数来自我的程序。

问题1:更新查询的计划是否被重用?或者优化器是否认为批处理文本不同并且不分析批处理中的单个查询?也就是说,是不是和

一样
update MyTable
set MyField = getutcdate()
where Id in (1, 2, 3 ...)

问题 2:我可以通过引入带有 table 参数的存储过程来强制 SQL 在调用之间保持相同,但是我会受益于是吗?

问题 3:如何识别给定查询的计划是否被重用或再次计算?

问题 4:在我的具体情况下,我是否应该担心以上所有问题?毕竟这只是对一堆 ID 的 table 的更新...

只是回答你的问题..

Question 1: does the plan for update query get reused? Or does optimizer look that text of batch is different and does not analyze single queries in batch? In other words, is it the same as

您的两个更新语句都被视为新查询,因为 SQL 尝试计算查询的散列,任何简单的更改都不会与旧散列相匹配

Question 2: I can force SQL to remain the same between calls by introducing a stored procedure with table parameter, but will I benefit from it?

这对我来说听起来是个好方法..而不是一堆 IN's

Question 3: how to identify for a given query whether its plan was reused or computed again?

select usecounts from sys.dm_exec_cached_plans ec
cross apply
sys.dm_exec_sql_text(ec.plan_handle) txt
where  txt.text like '%your query text%'

Question 4: should I worry about all above in my specific case? After all it is just an update of table on bunch of IDs...

在我看来,你很担心..正如你提到的白皮书中指出的那样,有很多规则强制执行查询计划重用行为..所以大多数时候,查询计划将被重用..

只有当我看到高 SQL Compilations/sec 加上 Batch Requests/sec

时,我才会开始担心计划的可重用性

取自这里的答案:https://dba.stackexchange.com/questions/19544/how-badly-do-sql-compilations-impact-the-performance-of-sql-server

SQL Compilations/sec is a good metric, but only when coupled with Batch Requests/sec. By itself, compilations per sec doesn't really tell you much.

You are seeing 170. If batch req per sec is only 200 (a little exaggerated for effect) then yes, you need to get down to the bottom of the cause (most likely an overuse of ad hoc querying and single-use plans). But if your batch req per sec is measuring about 5000 then 170 compilations per sec is not bad at all. It's a general rule of thumb that Compilations/sec should be at 10% or less than total Batch Requests/sec.