Reputation: 95
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??
Upvotes: 0
Views: 122
Reputation: 1271111
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)
Upvotes: 3