DateTime2 vs DateTime in SQL Server

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

    Here is an example that will show you the differences in storage size (bytes) and precision between smalldatetime, datetime, datetime2(0), and datetime2(7):

    DECLARE @temp TABLE (
        sdt smalldatetime,
        dt datetime,
        dt20 datetime2(0),
        dt27 datetime2(7)
    )
    
    INSERT @temp
    SELECT getdate(),getdate(),getdate(),getdate()
    
    SELECT sdt,DATALENGTH(sdt) as sdt_bytes,
        dt,DATALENGTH(dt) as dt_bytes,
        dt20,DATALENGTH(dt20) as dt20_bytes,
        dt27, DATALENGTH(dt27) as dt27_bytes FROM @temp
    

    which returns

    sdt                  sdt_bytes  dt                       dt_bytes  dt20                 dt20_bytes  dt27                         dt27_bytes
    -------------------  ---------  -----------------------  --------  -------------------  ----------  ---------------------------  ----------
    2015-09-11 11:26:00  4          2015-09-11 11:25:42.417  8         2015-09-11 11:25:42  6           2015-09-11 11:25:42.4170000  8
    

    So if I want to store information down to the second - but not to the millisecond - I can save 2 bytes each if I use datetime2(0) instead of datetime or datetime2(7).

提交回复
热议问题