SQL Server 2016中的随机缓慢查询性能

时间:2018-11-19 15:48:35

标签: sql performance sql-server-2016 sql-server-profiler

我会看到你是什么问题...

SELECT 
    SUM(A.POSTEDQTY),
    SUM(A.POSTEDVALUE),
    SUM(A.PHYSICALVALUE),
    SUM(A.DEDUCTED),
    SUM(A.RECEIVED),
    SUM(A.RESERVPHYSICAL),
    SUM(A.RESERVORDERED),
    SUM(A.REGISTERED),
    SUM(A.PICKED), 
    SUM(A.ONORDER),
    SUM(A.ORDERED),
    SUM(A.ARRIVED),
    SUM(A.QUOTATIONRECEIPT),
    SUM(A.QUOTATIONISSUE),
    SUM(A.AVAILPHYSICAL),
    SUM(A.AVAILORDERED),
    SUM(A.PHYSICALINVENT) 
FROM 
    INVENTSUM A WITH(NOLOCK) 
WHERE 
    ((A.DATAAREAID = @P1) 
    AND ((A.ITEMID = @P2) 
    AND (A.CLOSED = @P3))) 
    AND EXISTS (SELECT 'x' FROM INVENTDIM B WITH (NOLOCK) 
                WHERE ((B.DATAAREAID = @P4) 
                  AND ((((B.INVENTDIMID = A.INVENTDIMID) AND (B.CONFIGID = @P5)) 
                  AND (B.INVENTLOCATIONID = @P6)) AND (B.INVENTBATCHID = @P7))))

Query slow performance

declare @p2 int
set @p2=180157421
declare @p3 int
set @p3=16
declare @p4 int
set @p4=1
declare @p5 int
set @p5=1
exec sp_cursorexecute 1073741895,@p2 output,@p3 output,@p4 output,@p5 output,N'ens',N'V89710821',0,N'ens',N'PO16628',N'AS',N'OFS028748'
select @p2, @p3, @p4, @p5

Query parameters slow performance

SELECT SUM(A.POSTEDQTY),SUM(A.POSTEDVALUE),SUM(A.PHYSICALVALUE),SUM(A.DEDUCTED),SUM(A.RECEIVED),SUM(A.RESERVPHYSICAL),SUM(A.RESERVORDERED),SUM(A.REGISTERED),SUM(A.PICKED),SUM(A.ONORDER),SUM(A.ORDERED),SUM(A.ARRIVED),SUM(A.QUOTATIONRECEIPT),SUM(A.QUOTATIONISSUE),SUM(A.AVAILPHYSICAL),SUM(A.AVAILORDERED),SUM(A.PHYSICALINVENT) FROM INVENTSUMDELTA A WHERE ((A.DATAAREAID=@P1) AND (((A.ITEMID=@P2) AND (A.ISAGGREGATED=@P3)) AND (A.TTSID=@P4))) AND EXISTS (SELECT 'x' FROM INVENTDIM B WHERE ((B.DATAAREAID=@P5) AND ((((B.INVENTDIMID=A.INVENTDIMID) AND (B.CONFIGID=@P6)) AND (B.INVENTLOCATIONID=@P7)) AND (B.INVENTBATCHID=@P8))))

Same query good performance

declare @p2 int
set @p2=180157423
declare @p3 int
set @p3=16
declare @p4 int
set @p4=1
declare @p5 int
set @p5=1
exec sp_cursorexecute 1073741904,@p2 output,@p3 output,@p4 output,@p5 output,N'ens',N'V89710821',0,5666550353,N'ens',N'PO16628',N'AS',N'OFS028748'
select @p2, @p3, @p4, @p5

Parameters same query good performance

在SQLServer Profiler中,您可以看到同一查询在0ms或10000ms以上执行

如果我尝试直接使用相同的参数执行相同的查询(10000毫秒),则需要0毫秒

发生了什么事?

谢谢!! :)

1 个答案:

答案 0 :(得分:0)

第一次执行查询时,db引擎必须准备发送到db的语句,以搜索数据并返回结果。第二次该语句已经准备好并且数据在高速缓存上。这就是为什么第二轮运行总是更快

https://littlekendra.com/2016/11/25/why-is-my-query-faster-the-second-time-it-runs-dear-sql-dba-episode-23/