SQL Server slow results with parameters

拥有回忆 提交于 2019-12-24 01:25:07

问题


I have a query which selects some data, I pass some parameters in it:

DECLARE @FromAccDocNo     INT = 1,
        @ToAccDocNo       INT = 999999999,
        @FromDate         CHAR(10) = '1900/01/01',
        @ToDate           CHAR(10) = '2999/12/30',
        @L1Code           INT = 129

SELECT ad.AccDocNo,
       ad.AccDocDate,
       add1.Row,
       add1.RowComment,
       add1.Debit,
       add1.Credit
FROM   AccDoc ad
       INNER JOIN AccDocDetail add1
            ON  add1.AccDocNo = ad.AccDocNo
       INNER JOIN Topic t
            ON  t.TopicCode = add1.TopicCode
WHERE  t.L1Code = @L1Code -- here is the difference
       AND add1.AccDocNo BETWEEN @FromAccDocNo AND @ToAccDocNo
       AND ad.EffectiveDate BETWEEN @FromDate AND @ToDate
ORDER BY
       ad.AccDocNo

In first, I write the value 129 explicitly as @L1Code (it takes 0.010 sec)

In second form I pass @L1Code into query (it takes 2.500 sec)

Can anyone explain what happens?


回答1:


Please read the canonical reference: Slow in the Application, Fast in SSMS? (specifically this bit)

One way to fix, is to add OPTION (RECOMPILE) at the end of the query.



来源:https://stackoverflow.com/questions/19465003/sql-server-slow-results-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!