我可以更快地使这个存储过程

时间:2016-03-06 10:07:12

标签: sql sql-server performance subquery

我有下面的存储过程。即使在我的开发人员计算机上,此存储过程也会在3-4秒内运行,但在服务器上则需要15-20秒。我试图改变一些子查询来交叉应用,一些子外部应用。但它导致需要更长的时间。

@startDate datetime ,
@endDate datetime ,
@customerId int

;WITH t1(Plate,UsedFuelTypeUID,RemainingBefore,DateRangeTotal,DateRangeTransactionsTotal,RemaininCurrent) AS
(
select  
v.Plate, v.UsedFuelTypeUID,

isnull((select isnull( sum(vls1.FT_TotalLimit),0) 
    from VehicleChildLog vls1 
    where vls1.VehicleChildId =v.VehicleID and vls1.UpdateDate < @startDate  
    ),0)-
isnull((select isnull( sum(t1.Liter),0) from Transactions t1
    where t1.VehicleChildID=v.VehicleID and t1.SaleDate <@startDate
    ),0)as RemainingBefore,

sum(vl.FT_TotalLimit) DateRangeTotal,

isnull((select isnull( sum(t1.Liter),0) from Transactions t1
where t1.VehicleChildID=v.VehicleID and t1.SaleDate between @startDate and @endDate
),0) as DateRangeTransactionsTotal,

(v.FT_TotalLimit - v.FT_UsedTotalLimit) as RemainingCurrent

from VehicleChildLog vl
inner join VehiclesChild v on vl.VehicleChildId = v.VehicleID
where vl.CustomerChildID = @customerId and vl.UpdateDate between @startDate and @endDate
group by 
v.VehicleID, v.Plate, v.UsedFuelTypeUID
,v.FT_TotalLimit - v.FT_UsedTotalLimit
)

select *, t1.RemainingBefore+t1.DateRangeTotal-t1.DateRangeTransactionsTotal as RemainingAfter from t1 ;

表格结构如下

[Transactions]
(
    [TransactionID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [SaleDate] [datetime] NULL,
    [Liter] [float] NULL,
    [VehicleChildID] [int] NULL
...   
)

[VehiclesChild] 
(
    [VehicleID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerChildID] [int] NULL,
    [Plate] [varchar](16) NULL,
    [UsedFuelTypeUID] [int] NULL,
    [FT_TotalLimit] [float] NULL,
    [FT_UsedTotalLimit] [float] NULL
    ...
)

[VehicleChildLog]
(
    [VehiclesChildLogId] [int] IDENTITY(1,1) NOT NULL,
    [VehicleChildId] [int] NOT NULL,
    [CustomerChildId] [int] NOT NULL,
    [FT_TotalLimit] [float] NULL,
    [FT_UsedTotalLimit] [float] NULL,
    [UpdateDate] [datetime] NULL
    ...
)

0 个答案:

没有答案