Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Query Returning Items It Shouldn't Be

Here's the scenario. The column in question is called 'datein' and it's type is 'datetime'. I have three rows with the value of '2009-10-01 00:00:00.000' for 'datein'. Why does this query return the aforementioned rows?

SELECT  *
FROM    t_call AS tc
WHERE   tc.datein >= '2009-09-30 00:00:00.000'
        AND tc.datein <= '2009-09-30 23:59:59.999'

Using

SELECT  *
FROM    t_call AS tc
WHERE   tc.datein BETWEEN '2009-09-30 00:00:00.000'
        AND '2009-09-30 23:59:59.999'

returns the same result

like image 400
GregD Avatar asked Aug 08 '26 20:08

GregD


2 Answers

It's the lack of precision in the thousandths of a second value. Try ".997" instead.

MSDN DateTime documentation

Run this and you'll see:

declare @dt datetime

select @dt = '2009-09-30 23:59:59.999'
select @dt
like image 172
Austin Salonen Avatar answered Aug 10 '26 09:08

Austin Salonen


The DATETIME accuracy is 0.00333 seconds. So you need to go to '2009-09-30 23:59:59.998' so it doesn't round up to Oct 1st.

For example:

select '2009-09-30 23:59:59.994', 
  cast('2009-09-30 23:59:59.994' as datetime)
union all select '2009-09-30 23:59:59.995', 
  cast('2009-09-30 23:59:59.995' as datetime)
union all select '2009-09-30 23:59:59.996', 
  cast('2009-09-30 23:59:59.996' as datetime)
union all select '2009-09-30 23:59:59.997', 
  cast('2009-09-30 23:59:59.997' as datetime)
union all select '2009-09-30 23:59:59.998', 
  cast('2009-09-30 23:59:59.998' as datetime)
union all select '2009-09-30 23:59:59.999', 
  cast('2009-09-30 23:59:59.999' as datetime)

returns:

2009-09-30 23:59:59.994 2009-09-30 23:59:59.993
2009-09-30 23:59:59.995 2009-09-30 23:59:59.997
2009-09-30 23:59:59.996 2009-09-30 23:59:59.997
2009-09-30 23:59:59.997 2009-09-30 23:59:59.997
2009-09-30 23:59:59.998 2009-09-30 23:59:59.997
2009-09-30 23:59:59.999 2009-10-01 00:00:00.000
like image 40
Remus Rusanu Avatar answered Aug 10 '26 10:08

Remus Rusanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!