What is the optimal way to compare dates in Microsoft SQL server?

前端 未结 4 1394
别跟我提以往
别跟我提以往 2020-12-25 11:27

I have a SQL datetime field in a very large table. It\'s indexed and needs to be queried.

The problem is that SQL always stores the time component (even

4条回答
  •  盖世英雄少女心
    2020-12-25 12:15

    Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

    From that article:

    DECLARE @dateVar datetime = '19700204';
    
    -- Quickest when there is an index on t.[DateColumn], 
    -- because CONVERT can still use the index.
    SELECT t.[DateColumn]
    FROM MyTable t
    WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
    
    -- Quicker when there is no index on t.[DateColumn]
    DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
    SELECT t.[DateColumn] 
    FROM MyTable t
    WHERE t.[DateColumn] >= @dateVar AND 
          t.[DateColumn] < @dateEnd;
    

    Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

提交回复
热议问题