查询计划在没有实际涉及行的情况下显示插入成本为54%

use*_*474 6 sql-server sql-execution-plan

在我的一个查询中,有一个insert数据到临时表中.查看查询计划,它显示临时表中的实际插入占用了54%(只是将数据插入临时表).但是,没有行插入临时表.

为什么在没有插入行时计划显示非零值?

Mar*_*ith 3

即使在实际的查询计划中,显示的子树成本也是基于估计以及基于成本的优化器使用的各种启发法和幻数。它们可能是严重错误的,因此在服用时应持保留态度。

重现示例

create table #t
(
i int
)

insert into #t
select number
from master.dbo.spt_values
where number = 99999999
Run Code Online (Sandbox Code Playgroud)

计划

实际插入为零行,但估计为 1 行,这就是子树成本的来源。

编辑:我刚刚尝试了以下操作

insert into #t
select top 0 number
from master.dbo.spt_values
where number = 99999999
Run Code Online (Sandbox Code Playgroud)

计划

即使它获得了正确的估计行数,它仍然会为插入分配一个小的非零成本。我猜想它使用的启发式总是分配固定成本的一些小元素。