我有问题找出为什么一个查询要花费更长的时间运行基于我换出一个参数与真实值。SQL查询执行使用参数
DECLARE @quarter int
DECLARE @year int
DECLARE @countOfUnitsBought int
set @year = 2009
set @quarter = 1
set @countOfUnitsBought = 4;
with res
as
(
select
o.account_id
--,orderyear
--,orderquarter
from
fmtables.[dbo].[orders] o
--cross apply(values(year(o.[ship_date]))) as a1(orderyear)
--cross apply(values(DatePart(quarter,(o.[ship_date])))) as a2(orderquarter)
where
ship_date = (select min(ship_date) from fmtables.[dbo].[orders] mo where [account_id] = o.account_id) and
total_value > 0 AND
order_status NOT LIKE 'return%' AND
order_status NOT LIKE 'cancel%' AND
order_status NOT LIKE 'freeze%' and
CAST(DatePart(quarter,(o.[ship_date])) as int) = @quarter and
year(o.[ship_date]) = @year and
(select sum(quantity) from fmtables..[orders] ox inner join fmtables..[orderlines] olx on ox.order_id = olx.order_id
where olx.order_id = o.order_id and [product_code] in(select [product_code] from fmtables..[products] where [category_code] in('1','2','3','4'))) >= @countOfUnitsBought
)
select * from res;
此查询需要43秒才能运行。
现在,如果我只需更换@quarter和改变文字
CAST(DatePart(quarter,(o.[ship_date])) as int) = 1 and
现在只需1秒。
任何人都可以请给我一个线索,为什么,如果我需要改变一些铸件来帮助。 感谢 斯科特
编辑:
所以我设法得到它嗖嗖通过与大家的意见帮助。 我使用了从输入中传递参数,然后通过过程中的“本地”变量的混合。
alter procedure [dbo].[Lifetime_HeadsetUnits]
@inquarter int , @inyear int, @incountOfUnitsBought int
as
DECLARE @quarter int
DECLARE @year int
declare @countOfUnitsBought int
select @quarter = @inquarter
select @year = @inyear
select @countOfUnitsBought = @incountOfUnitsBought
并且还 OPTION(OPTIMIZE FOR(@quarter = 1))
作为最终输出查询的一部分。
解决相同的问题在这里描述:http://stackoverflow.com/questions/11119432/parameter-doesnt-perform-as-well-as-hard-coding-the-value - 你可能会开始通过尝试'OPTION(OPTIMIZE FOR(@quarter = 1))' – 2015-03-03 13:53:45
您是否知道如何查看查询计划?如果这是你真正的疑问,而不仅仅是为了这个问题的演示,那么看到两种选择之间的区别不应该太难。 – 2015-03-03 13:55:51
@quarter的值将随着它进入一个循环而改变。我会看看选项设置。谢谢 – scottsanpedro 2015-03-03 13:59:03