Search code examples
sql-serverdatetimesql-server-2017

Why do I get datetime conversion out of range for 999 milliseconds?


Could someone please explain me, why I get the error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

when I execute the following code on SQL Server 2017. I get the error only for .999 milliseconds

SELECT CAST('9999-12-31 23:59:59.999' AS DATETIME)

Result:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Then I tried:

SELECT CAST('9999-12-31 23:59:59.998' AS DATETIME)

Result: 9999-12-31 23:59:59.997

Then I tried:

SELECT CAST('9999-12-31 23:59:59.997' AS DATETIME)

Result: 9999-12-31 23:59:59.997


Solution

  • Based on documentation the datetime range is between January 1, 1753 and December 31, 9999. Also still based on documentation the time range is between 00 to 23:59:997.

    So if you make a rounding, at 998 it will round down to 997. At 999 it should round up to January 01 10000 which is out of range. (the precision of datetime in sql-server is 3.33ms)