使用参数执行SQL查询

时间:2015-03-03 13:48:21

标签: sql sql-server tsql

我在查明为什么基于我将参数与实际值交换时查询运行时间大得多的问题时,我遇到了问题。

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秒钟。

任何人都可以给我一个线索,了解为什么以及我是否需要改变一些演员来提供帮助。 谢谢 斯科特

编辑:

所以我设法通过每个人的评论来帮助它。 我使用了从输入传递参数然后到过程中的'local'变量的混合。

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

还有     选项(OPTIMIZE FOR(@quarter = 1))
作为最终输出查询的一部分。

1 个答案:

答案 0 :(得分:1)

试试这个。我重写了datepart,因此可以使用索引,数据库不会对所有行进行长计算。换句话说,我做了你的日期计算sargable

DECLARE @quarter int
DECLARE @year int
DECLARE @countOfUnitsBought int

set @year = 2009
set @quarter = 1
declare @from datetime = dateadd(quarter, @quarter - 1, cast(@year as char(4)))

set @countOfUnitsBought = 4;

with res
as
(
  select
  o.account_id
  from
    fmtables.[dbo].[orders] o     
  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   
   o.[ship_date] >= @quarter and
   o.[ship_date] < DATEADD(QUARTER, 1, @from) and
    (select sum(quantity) from fmtables..[orders] ox    
    inner join fmtables..[orderlines] olx on ox.order_id = olx.order_id  
    where [product_code] in(select [product_code] from fmtables..[products] 
    where [category_code] in('1','2','3','4'))) >= @countOfUnitsBought
)
select * from res;

你在运行sql-server 2008吗?有bug也可以解释您的效果问题。