Hossein POURAKBAR
Hossein POURAKBAR

Reputation: 1181

SQL Server slow results with parameters

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?

Upvotes: 2

Views: 219

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300539

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.

Upvotes: 3

Related Questions