I need to select all records from my SQL Server database that falls between a certain hour. Let me give you an example:
Current time is 9:33 am and you have numerous Program records in the database that have an ProgramStart and ProgramEnd. An example of the dates might be:
| ProgramStart | ProgramEnd | ClientID |
+--------------------------+-------------------------+----------+
| 1900-01-01 09:00:00.000 | 1900-01-01 10:00:00.000 | 5 |
+--------------------------+-------------------------+----------+
| 1900-01-01 11:00:00.000 | 1900-01-01 13:00:00.000 | 4 |
+--------------------------+-------------------------+----------+
| 1900-01-01 12:00:00.000 | 1900-01-01 14:00:00.000 | 5 |
+--------------------------+-------------------------+----------+
| 1900-01-01 11:00:00.000 | 1900-01-01 13:00:00.000 | 6 |
+--------------------------+-------------------------+----------+
| 1900-01-01 16:00:00.000 | 1900-01-01 17:00:00.000 | 7 |
+--------------------------+-------------------------+----------+
| 1900-01-01 16:00:00.000 | 1900-01-01 17:00:00.000 | 5 |
+--------------------------+-------------------------+----------+
| 1900-01-01 17:00:00.000 | 1900-01-01 18:00:00.000 | 4 |
+--------------------------+-------------------------+----------+
I want to extract all records for client 5 and between the current time which is 9:33am
How does one do that with SQL. I tried this, but it doesn’t work:
SELECT CAST('1900-01-01 09:33:00.000' AS datetime) AS TimeNow, * FROM Programs
WHERE ClientID = 5
AND TimeNow BETWEEN '1900-01-01 09:00:00.000' AND '1900-01-01 10:00:00.000'
any suggestions would be greatly appreciated.
Many thanks,
Paul
1 Answer