Compare time part of DateTime data type in SQL Server 2005
What I wanted to do is to extract the time portion of a DateTime data type, and compare it. I found a way to extract the date portion here in StackOverflow. If I have the date part alone, it is just subtract the date from the source DateTime:
datePortion = DATEADD(day, DATEDIFF(day,0, sourceDate), 0)
timePortion = DATEDIFF(millisecond, datePortion, sourceDate)
so the macro to extract the time portion in SQL Server 2005 is:
f(x) = DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day,0, sourceDate), 0), sourceDate)
Now the query to compare the time portion of a DateTime field, with 12:30:50.400 is:
SELECT *
FROM Table1
WHERE
DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day, 0, DateTimeField), 0), DateTimeField)
>
DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day, 0, '1900-01-01T12:30:50.400'), 0), '1900-01-01T12:30:50.400')
I have tested this query against other kinds of queries, including using subtraction operator ('-'), and CONVERT. The execution plan comparison indicates that this is the fastest method to do this. I also tested the real times of query execution... there is no noticeable fastest method.
SELECT *
FROM Table1
WHERE DATEADD(day, -DATEDIFF(day, 0, MyDateField), MyDateField) > '12:30:50.400'
How about this?
SELECT (fields)
FROM dbo.YourTable
WHERE DATEPART(HOUR, MyDate) >= 12
AND DATEPART(MINUTE, MyDate) >= 23
AND DATEPART(SECOND, MyDate) >= 45
The hour is given in the 24-hour format, e.g. 12 means 12 hour noon, 15 means 3pm.
DATEPART
also has "parts" for minutes, seconds and so forth. You can of course use as many of those date parts in your WHERE clause as you like.