Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Sql server how to select time range between two columns times. Can any one explain how to do ASAP

What I have tried:

select * from tablename
where starttime < @starttime
and endtime > @entime
Posted
Updated 27-Aug-17 20:03pm
Comments
Richard Deeming 29-Aug-17 14:15pm    
where starttime < @starttime and endtime > @endtime
At a guess, that's your problem: you're looking for records which start before the specified start time, and end after the specified end time.

If you want to select records which fall between the specified start and end times, you're going to need to reverse those operators:
where starttime >= @starttime and endtime <= @endtime

1 solution

When you get problems like this, it's often because the database has been designed wrong.
Start by checking the column definitions: if starttime and endtime are not DATE, DATETIME, or DATETIME2 columns, then no date-related queries will work as they will be treated as string =-based comparisons. With those, the entire comparison is based on the first different character in the two strings, so "01-01-2017' comes before "31-12-2016" and so forth.

If the columns are ok, check the parameter values: again these should be DateTime values in your native presentation language that passes them, not strings - otherwise SQL has to "guess" if they are "dd-mm-yy", "mm-dd-yy", or "yy-dd-mm" and it will frequently get it wrong.

If that's all OK, look at the data, and the parameter values manually, and check that some values exist that match both condition.

Sorry, but we can't do any of that: we have no access to your code or data!
 
Share this answer
 
Comments
Member 12523149 28-Aug-17 2:12am    
Thank for your quick replay. My starttime and endtime time datatype i have used and stored like this (HH:mm:ss) and how to compare between two times
OriginalGriff 28-Aug-17 2:22am    
And?
"look at the data, and the parameter values manually, and check that some values exist that match both condition."
What did you find?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900