What you want to do is add them together and then compare to get date. Unfortunately, you cannot add a date
and time
together. Happily, you can add a datetime
and time
together.
So:
WHERE (CAST(date as datetime) + time) >= DATEADD(HOUR, -2, GETDATE())
If time
is character, then you should be able to convert that as well:
WHERE (CAST(date as datetime) + CAST(time as time)) >= DATEADD(HOUR, -2, GETDATE())
Or, if the PM is redundantly part of the time
, then:
WHERE (CAST(date as datetime) + CAST(LEFT(time, 8) as time)) >= DATEADD(HOUR, -2, GETDATE())
Unfortunately, this will not use an index. But, one simple method is to use a computed column and an index:
alter table report add datetimecol as (CAST(date as datetime) + time);
create index idx_report_datetimecol on report(datetimecol);
EDIT:
You seem to have a problem with your data. Try:
select time
from report
where try_convert(time, timecol) is null;
or:
select time
from report
where try_convert(time, left(timecol, 8)) is null;
If the date column is also a string (really bad idea to not use native data types), then test that as well.