I have a question about converting a string to a date format in SQL/Server. I have a column called EDATE and it holds a string of 6 characters in the format MMDDYY. When I create a recordset I want to sort it by this column. Right now though it does not recognize it as a date format. How can I convert it to a date format and then sort it by date? Thanks for your help.
There are two ways to approach this. One is to do a date conversion, and then sort on the date column. Your first attempt at this might be --
select cast(EDATE as datetime) as sortdate [ , other columns ] from yourtable order by sortdate
The problem with the above is that SQL/Server interprets a 6-digit date as YYMMDD format. So you would have to do some clever substringing --
select cast( substring(EDATE,5,2) /* yy */ + substring(EDATE,1,4) /* mmdd */ as datetime) as sortdate [ , other columns ] from yourtable order by sortdate
The above query assumes that the date conversion runs without errors. (Consider what happens if the EDATE character field does not have a valid 6-digit MMDDYY string in it.)
An alternate approach is simply to sort by the substrings --
select substring(EDATE,5,2) as yy , substring(EDATE,1,4) as mmdd [ , other columns ] from yourtable order by yy, mmdd
This is simpler, in my opinion, because it avoids a conversion, which can affect performance efficiency.
For More Information
- What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.