72

I have a table structured like this:

CREATE TABLE [TESTTABLE]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [DateField] [datetime] NULL,
    [StringField] [varchar](50),
    [IntField] [int] NULL,
    [BitField] [bit] NULL
)

I execute the following code:

BEGIN 
   INSERT INTO TESTTABLE (IntField, BitField, StringField, DateField) 
   VALUES ('1', 1, 'hello', {ts '2009-04-03 15:41:27.378'});  

   SELECT SCOPE_IDENTITY()  
END

And then

select * from testtable with (NOLOCK)

and my result shows:

2009-04-03 15:41:27.*377*

for the DateField column.

Any ideas why I seem to be losing a millisecond??

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
sproketboy
  • 8,967
  • 18
  • 65
  • 95

6 Answers6

100

SQL Server only stores time to approximately 1/300th of a second. These always fall on the 0, 3 and 7 milliseconds. E.g. counting up from 0 in the smallest increment:

00:00:00.000
00:00:00.003
00:00:00.007
00:00:00.010
00:00:00.013
...

If you need that millisecond accuracy, there's no pleasant way around it. The best options I've seen are to store the value in custom number fields and rebuild it every time you fetch the value, or to store it as a string of a known format. You can then (optionally) store an 'approximate' date in the native date type for the sake of speed, but it introduces a conceptual complexity that often isn't wanted.

Whatsit
  • 10,227
  • 11
  • 42
  • 41
  • 13
    Be sure to read Rob Garrison's post about TIME and DATETIME2 -- these types have much higher resolution. – Dave Markle Aug 17 '12 at 18:28
  • According to my tests on Azure SQL as of today, all of my DateTime fields have milliseconds with ones digits of 0, 3, and 6 – Jason Dufair Apr 03 '20 at 18:38
45

SQL Server 2008 has much more precision available. The datetime2 type will accurately store values like this: 2008-12-19 09:31:38.5670514 (accuracy to 100 nanoseconds).

Reference: time and datetime2 - Exploring SQL Server 2008's New Date/Time Data Types

nikib3ro
  • 20,366
  • 24
  • 120
  • 181
Rob Garrison
  • 6,984
  • 4
  • 25
  • 23
29

The SQL Server datetime type only has a 1/300th of a second (~3.33̅ ms) resolution, so you are probably seeing a rounding error.

See the MSDN Datetime SQL Server reference

Eli Rose
  • 6,788
  • 8
  • 35
  • 55
Peter M
  • 7,309
  • 3
  • 50
  • 91
7

SQL Server is only accurate to 1/300th of a second. It will round values to the nearest 1/300th.

TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116
Tom H
  • 46,766
  • 14
  • 87
  • 128
3

DATETIME does not have infinite precision - you are probably using a value that cannot accurately be represented with the available bits.

2

SQL Server stores datetime values to a precision of 3 milliseconds. (I've heard about this, but can't find an official reference.)

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
bdukes
  • 152,002
  • 23
  • 148
  • 175