Home > Enterprise >  DateTime condition in where clause doesnt work correctly
DateTime condition in where clause doesnt work correctly

Time:11-02

I have row in my table with first column datetime type:

2021-11-01 08:51:56.123 102 296 

When I use the select commands below, I get same result (this row):

select * from  cmd where timestamp = convert(datetime, '2021-11-01 08:51:56.122')
select * from  cmd where timestamp = convert(datetime, '2021-11-01 08:51:56.123')
select * from  cmd where timestamp = convert(datetime, '2021-11-01 08:51:56.124')

I request that only the second command picks this line.

How to do it?

SQL Server is version 14

CodePudding user response:

DATETIME has a precision of (about) .003 seconds. This means it can represent only every 3rd thousands of a second and everything else is rounded to increments of .000, .003, or .007 seconds, as shown in the following table.

User-specified value    System stored value
01/01/98 23:59:59.999   1998-01-02 00:00:00.000
01/01/98 23:59:59.995

01/01/98 23:59:59.996

01/01/98 23:59:59.997

01/01/98 23:59:59.998   1998-01-01 23:59:59.997
01/01/98 23:59:59.992

01/01/98 23:59:59.993

01/01/98 23:59:59.994   1998-01-01 23:59:59.993
01/01/98 23:59:59.990

01/01/98 23:59:59.991   1998-01-01 23:59:59.990

You can use DATETIME2(3) instead of DATETIME for more precision.

For more details, please read https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15

  • Related