tags:

views:

744

answers:

7

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 date field.

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

TIA

+2  A: 

SQL Server is only accurate to 3/1000ths of a second. It will round values to the nearest 3/1000ths.

Tom H.
Thanks for the responses. Makes me feel better. I just have to adjust my unit tests. :)
Dan Howard
Close, 3/1000 resolution would be 000, 003, 006, 009... 1/300 resolution is 000, 003, 007, 010...
Eclipse
+12  A: 

The MS-SQL Datetime only has a 3.3mS resolution, so you are probably seeing a rounding error.

See the MSDN Datetime SQL reference

Peter M
+2  A: 

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

bdukes
+2  A: 

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

anon
+3  A: 

See this question for more details

John M Gant
+7  A: 

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
+5  A: 

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

Rob Garrison