SQL Server使用参数缓慢结果

时间:2013-10-19 10:26:46

标签: sql-server performance parameters

我有一个选择一些数据的查询,我在其中传递了一些参数:

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

首先,我将值129显式写为@L1Code(需要0.010秒)

在第二种形式中,我将@L1Code传递给查询(需要2.500秒)

任何人都能解释会发生什么吗?

1 个答案:

答案 0 :(得分:3)

请阅读规范参考:Slow in the Application, Fast in SSMS?(特别是此bit

一种解决方法是在查询结尾处添加OPTION (RECOMPILE)