Sorting by StartDateTime

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.

See also  Small Business Strategies with Venmo

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist