Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have a table with a field ie starttimes . What I need is that , I need to get all the starttimes that is greater than a particular time . I have stored the time in varchar type.

What I have tried:

For example ,
StartTimes
1:00 AM    
2:00 AM  
3:00 AM      
4:00 AM  
7:00 AM 
1:00 PM
2:00 PM
3:00 PM

and so on .
If I select 7:00 AM , I need to get all the times greater than 7:00 AM ie all times in time field within 12 Hrs ie from 7:00 AM TO 11:59 PM.How to do this.
Any help will be really appreciated .Thanks in Advance.
Posted
Updated 3-Jul-18 1:46am
v2
Comments
CHill60 3-Jul-18 7:38am    
Easy answer is don't use Varchar type for Time ... use, er, Time
Maciej Los 3-Jul-18 10:57am    
My virtual 5!

Using this sample data
create table #badway
(
	id integer identity(1,1),
	mytime varchar(8)
)
insert into #badway (mytime) values
('1:00 AM'),
('2:00 AM'),  
('3:00 AM'),      
('4:00 AM'),  
('7:00 AM'), 
('1:00 PM'),
('2:00 PM'),
('3:00 PM')
Then this query fits your criteria
SQL
select id, convert(time, mytime) from #badway
where convert(time, mytime) between '07:00:00' and '23:59:00'
Note the use of the 24hr clock.

As I said in my comment, you should use time column types to store times, not varchar, then there would be no need for the convert
 
Share this answer
 
Comments
Maciej Los 3-Jul-18 10:57am    
And the real one: 5!
Use SQL Server DATEPART() Function[^].
SQL
SELECT * FROM [your table] WHERE DATEPART(hh, [your date field]) = 7 --7 AM

KR
 
Share this answer
 
v2
Comments
CHill60 3-Jul-18 7:48am    
You were closer with v1 of this solution. You actually mean
SELECT * FROM [your table] WHERE DATEPART(hh, [your date field]) >= 7

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