I just run this query
Select *
from ProjectData
where logtime between '2012-09-25 12:00:00.000' and '2012-09-25 12:59:59.999'
order by LogTime
in an attempt to find the all record for 12 hour, We have record every second, so I was expecting 3600 record but to my surprise I got 3601 record and the last record time was
2012-09-25 13:00:00.000
Any idea why this record is picked? Even if Between
includes the given values this value is above the condition. I am using SQL Server 2012 Express edition.
To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function.
The SQL BETWEEN Operator The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN '2001-03-01 11:00:00' AND '2005-03-01 22:00:00';
As mentioned above BETWEEN operator can be used along with numeric value, text value, and date.
Try to use DATETIME2
datatype for logtime
column -
Query:
DECLARE @temp TABLE (logtime DATETIME2)
INSERT INTO @temp (logtime)
VALUES
('20120925 12:00:00.000'),
('20120925 12:59:59.999'),
('20120925 13:00:00.000')
SELECT *
FROM @temp
WHERE logtime BETWEEN '2012-09-25 12:00:00.000' AND '2012-09-25 12:59:59.999'
ORDER BY logtime
Output:
logtime
---------------------------
2012-09-25 12:00:00.0000000
2012-09-25 12:59:59.9990000
DATETIME vs DATETIME2:
SELECT name, [precision]
FROM sys.types
WHERE name IN ('datetime', 'datetime2')
Output:
name precision
----------- ---------
datetime2 27
datetime 23
You have taken Datetime
as datatype and it has property of getting rounded.
Datetime
values are rounded to increments of .000, .003, or .007 seconds. Details here
Eg:
SQL Fiddle
MS SQL Server 2012 Schema Setup:
Query 1:
Declare @testtime datetime = '2012-09-25 12:59:59.999'
select @testtime
Results:
| COLUMN_0 |
------------------------------------
| September, 25 2012 13:00:00+0000 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With