Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: SQL Server
Expertise: Beginner
Jul 20, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Sorting by StartDateTime

I have a field called StartDateTime. In Microsoft Access it contained only a time. My code used to sort this field properly when outputting, so that morning events appeared at the top.

Since migrating to SQL Server, however, the field is now sorted by the first character, and the field contains dates in the 1800s that never used to be there. 9AM events appear right after 9PM events in my output.

So I ask:

1. How can I create just a TIME field for Microsoft SQL 7.0?

2. How can I sort the field properly (regardless of the answer for Question 1)?

I'm not clear about whether you have dates and times in your table now.

You can use the DATEPART function to extract the time from the datetime you have. Then you'll need to use the CONVERT function to change the data type of the date, because it is implicitly identified as an int.

The first thing to do is to get what you want out of the date.

SELECT DATEPART(hh,the_date) FROM MYTABLE will get you the hours portion of the datetime out of the field.

SELECT CONVERT(CHAR(2),DATEPART(hh, the_DATE)) will do the extraction and coerce the datatype into a character for you.

Hope this helps.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date