How can I compare only the time portion of a DateTime data type in SQL Server 2005? For example, I want to get all records in which MyDateField is after a specific time. The following example is a very long and probably not fast way of doing this. I want all dates where MyDateField is greater than 12:30:50.400
SELECT *
FROM Table1
WHERE ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) = 30) AND (DATEPART(second, MyDateField) = 50) AND (DATEPART(millisecond, MyDateField) > 400))
OR ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) = 30) AND (DATEPART(second, MyDateField) > 50))
OR ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) > 30))
OR ((DATEPART(hour, MyDateField) > 12))
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.
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