DateTime2 vs DateTime in SQL Server

前端 未结 14 1060
谎友^
谎友^ 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

    0 讨论(0)
  • 2020-11-22 06:52

    while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal. Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.

    If value compatability over precision, use datetime

    0 讨论(0)
提交回复
热议问题