Does SQL Server optimize DATEADD calculation in select query?

后端 未结 3 1636
轮回少年
轮回少年 2020-12-19 17:44

I have a query like this on Sql Server 2008:

DECLARE @START_DATE DATETIME
SET @START_DATE = GETDATE()

SELECT * FROM MY_TABLE
WHERE TRANSACTION_DATE_TIME >         


        
3条回答
  •  孤城傲影
    2020-12-19 18:08

    Surprisingly, I've found that using GETDATE() inline seems to be more efficient than performing this type of calculation beforehand.

    DECLARE @sd1 DATETIME, @sd2 DATETIME;
    SET @sd1 = GETDATE();
    
    SELECT * FROM dbo.table
    WHERE datetime_column > DATEADD(MINUTE, -1440, @sd1)
    
    SELECT * FROM dbo.table
    WHERE datetime_column > DATEADD(MINUTE, -1440, GETDATE())
    
    SET @sd2 = DATEADD(MINUTE, -1440, @sd1);
    
    SELECT * FROM dbo.table
    WHERE datetime_column > @sd2;
    

    If you check the plans on those, the middle query will always come out with the lowest cost (but not always the lowest elapsed time). Of course it may depend on your indexes and data, and you should not make any assumptions based on one query that the same pre-emptive optimization will work on another query. My instinct would be to not perform any calculations inline, and instead use the @sd2 variation above... but I've learned that I can't trust my instinct all the time and I can't make general assumptions based on behavior I experience in particular scenarios.

提交回复
热议问题