【发布时间】:2010-10-01 21:50:55
【问题描述】:
这很难解释,但我会尝试。
正如您在所附的 query_plan 图片上看到的(这是 “All in one place” 查询的查询计划,如下所述),有 3 个几乎相同的“块” - 我的问题是为什么?在我看来,当我有“all in one”(见下文)查询时,“Init”块(相当重)会使用不同的过滤器运行 3 次,而不是 SPOOLED 并在以后重复使用。
此查询执行时间约为 45 秒。 它的查询可以用以下形式呈现:
-- Complex "All in One place" Query
WITH init as (
Init1 complex query here -- (10 sec to run) if executed alone
)
, step1 as ( select * from init .. joins... where ... etc ),
step2 as ( select *, row_number() over(__condition__) as rn from step1 where _filter1_)
, step3 as ( select * from step2 where __filter2_),
.... some more steps could be here ....
select *
into target_table
from step_N;
-- 45sec CPU time
这里重要的是我在“WITH”子句中顺序使用那些 Step1、Step2、...、StepN 表 - 步骤 1 使用 INIT 表,所以 Step2 使用 Step1 表,Step3 使用 Step2 表等。我需要这个由于排名不同,我会在稍后用于过滤的每个步骤之后进行处理。
如果把这个复杂的 CTE 查询改成(我把 Init 查询的结果放到表中,然后处理其他步骤不变):
-- Complex query separated from the rest of the query
with Init as (
The same Init1 complex query here
)
select *
into test_init
from init;
-- 10sec CPU time
with step1 as ( select * from test_init .. joins... where ... etc ),
step2 as ( select *, row_number() over(__condition__) as rn from step1 where _filter1_) ,
step3 as ( select * from step2 where __filter2_),
.... some more steps could be here ....
select *
into target_table
from step_N;
-- 5sec CPU time
我有大约 15 秒的执行时间,这对我来说似乎没问题。因为 10 秒是第一个难以改进的复杂查询。
所以我不能得到这个 MS Sql server 2005 的行为?有人可以向我解释一下吗?我想这很有趣!
【问题讨论】:
标签: sql-server-2005 tsql sql-execution-plan