Sometimes you have the need to compare time without the date component. I have a table where I’m storing only TIME (e.g., 10:30:00 or 13:35:45) without the date component in Microsoft SQL server. If you try to use greater than (>), smaller than (<) or equal to operator (=) to compare a DATETIME or TIME data type, the SQL server may throw following error:
The data types datetime and time are incompatible in the greater than or equal to operator.
In order to overcome this error you will have to use the following trick/hack to compare datetime or time data types:
- First, CAST the TIME data type to DATETIME:
CAST(myTime as datetime)
- myTime is the name of my column; it’s SQL data type is TIME - CAST the above to FLOAT
CAST( CAST(myTime as datetime) as float) - Use the <, >, or = operator as:
SELECT CAST(CAST(myTime as datetime) as float) as myTimeAsNumber
FROM myTable
WHERE CAST(CAST(myTime as datetime) as float) <= CAST(CAST(‘14:15:00’ as datetime) as float)
- This will return all records on or before 02:45 PM. Usually Microsoft SQL server stores time in 24 hours format, i.e., 14:15:00.000 format.
After I CAST myTime as datetime and its result to float I got 0.75. That indicates 18 hours after 1/1/1900 (SQL Server’s base date), i.e., 75/100ths of a fractional day – it’s evening 6:00 PM. So when I’m casting my column as datetime and the result to float data type I end up with a number that is equal or smaller to 1.
Casting 24:00:00 time to datetime and the result to float will give 1, which indicates 24 hours (1 Day) after SQL server’s base date. And, casting 12:00:00 time to datetime and the result to float will give 0.5, which indicates 0.5 day or 12 hours.
Moreover, you may end up with following error if you try to cast time as float:
CAST(CAST(myTime as time) as float) will throw following error:
Explicit conversion from data type time to float is not allowed.
To fix this, cast data type time (myTime) as datetime and then cast the result as float as we have done above.
Make sure NOT to use FLOOR function as it will strip off decimal portion of number. Hope this post will be useful for people trying to compare datetime or time data types.