DateTime2 vs DateTime in SQL Server

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

    I concurr with @marc_s and @Adam_Poward -- DateTime2 is the preferred method moving forward. It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision).

    One thing the discussion missed, however...
    @Marc_s states: Both types map to System.DateTime in .NET - no difference there. This is correct, however, the inverse is not true...and it matters when doing date range searches (e.g. "find me all records modified on 5/5/2010").

    .NET's version of Datetime has similar range and precision to DateTime2. When mapping a .net Datetime down to the old SQL DateTime an implicit rounding occurs. The old SQL DateTime is accurate to 3 milliseconds. This means that 11:59:59.997 is as close as you can get to the end of the day. Anything higher is rounded up to the following day.

    Try this :

    declare @d1 datetime   = '5/5/2010 23:59:59.999'
    declare @d2 datetime2  = '5/5/2010 23:59:59.999'
    declare @d3 datetime   = '5/5/2010 23:59:59.997'
    select @d1 as 'IAmMay6BecauseOfRounding', @d2 'May5', @d3 'StillMay5Because2msEarlier'
    

    Avoiding this implicit rounding is a significant reason to move to DateTime2. Implicit rounding of dates clearly causes confusion:

    • Strange datetime behavior in SQL Server
    • http://bytes.com/topic/sql-server/answers/578416-weird-millisecond-part-datetime-data-sql-server-2000-a
    • SQL Server 2008 and milliseconds
    • http://improve.dk/archive/2011/06/16/getting-bit-by-datetime-rounding-or-why-235959-999-ltgt.aspx
    • http://milesquaretech.com/Blog/post/2011/09/12/DateTime-vs-DateTime2-SQL-is-Rounding-My-999-Milliseconds!.aspx

提交回复
热议问题