sql-server - 在 SQL Server 2012 中重用查询计划

标签 sql-server sql-server-2012 query-optimization sql-execution-plan

我正在使用 SQL Server,并且希望从重用查询计划中受益。我找到了这个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,我基本上会将表变量传递给 SQL 命令,但我使用的是 Python,看起来没有办法从我的程序传递表参数。

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

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

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

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

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

最佳答案

只是回答你的问题..

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

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编译/秒加上批量请求/秒时,我才会开始担心计划的可重用性

取自此处的答案: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.

关于sql-server - 在 SQL Server 2012 中重用查询计划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593960/

相关文章:

sql-server - 数据库层的业务逻辑

sql - 在 SQL Server 2008 中从一行设置多个标量变量?

sql - 哪一种是更快/更好的 sql 实践?

sql-server - 使用端口号的 SQL Server 名称

sql - 获取开始日期和结束日期 - 从给定年份 yyyy 开始

sql-server - SQL 服务器 - 估计执行时间并获取更改表命令的进度

php - 如何优化这个复杂的 MySql 查询

mysql - 有一种方法可以优化大型mysql查询吗?

python - pyodbc 连接到 SQL Server 2012 问题

sql-server - 带有子查询的 INSERT 的原子性