DateTime2 vs DateTime in SQL Server

前端 未结 14 1065
谎友^
谎友^ 2020-11-22 06:04

Which one:

  • datetime
  • datetime2

is the recommended way to store date and time in SQL Server 2008+?

I\'m aware of differ

14条回答
  •  盖世英雄少女心
    2020-11-22 06:50

    Old Question... But I want to add something not already stated by anyone here... (Note: This is my own observation, so don't ask for any reference)

    Datetime2 is faster when used in filter criteria.

    TLDR:

    In SQL 2016 I had a table with hundred thousand rows and a datetime column ENTRY_TIME because it was required to store the exact time up to seconds. While executing a complex query with many joins and a sub query, when I used where clause as:

    WHERE ENTRY_TIME >= '2017-01-01 00:00:00' AND ENTRY_TIME < '2018-01-01 00:00:00'
    

    The query was fine initially when there were hundreds of rows, but when number of rows increased, the query started to give this error:

    Execution Timeout Expired. The timeout period elapsed prior
    to completion of the operation or the server is not responding.
    

    I removed the where clause, and unexpectedly, the query was run in 1 sec, although now ALL rows for all dates were fetched. I run the inner query with where clause, and it took 85 seconds, and without where clause it took 0.01 secs.

    I came across many threads here for this issue as datetime filtering performance

    I optimized query a bit. But the real speed I got was by changing the datetime column to datetime2.

    Now the same query that timed out previously takes less than a second.

    cheers

提交回复
热议问题