I have a field in table that is varchar(12), however data in that field is a date - 1/1/2016 (I have about 5,000 dates). I've been trying to do an ORDER BY but it doesn't seem to order by the date. How would I go about doing ORDER BY on that field if it's not a DateTIME field??
2 Answers
Try:
Order by cast(Field as datetime) 1 Comment
vercelli
@LD16 Glad it helped. Gordon Linoff has a good point. Check his answer also.
The conversion of a date such as "1/1/2016" using CAST() depends on localization settings.
Assuming the value is in MM/DD/YYYY format (some countries do use DD/MM/YYYY), then this is more safely written as:
order by convert(datetime, field, 101) Then, you run the risk that the conversion may fail, if a field does not exactly match this format. To prevent this error, SQL Server 2012+ offers try_convert().
So, I think the best approach is:
order by try_convert(datetime, field, 101) 3 Comments
Martin AJ
. . . What's
101 ?Gordon Linoff
It is the silly method that SQL Server used to format dates before introducing
format(). It is a magic code, documented at msdn.microsoft.com/en-us/library/ms187928.aspx.LD16
Thankfully I only need this to query important data that is later copied. I'm not making any stored procedures or reusing it in code. thanks tho!
varcharinstead ofdate?