Order by date when stored as a nvarchar
by RedCoupe on Jul.21, 2011, under Web design / development
Just had a MS SQL Server problem where as the title suggests, I wanted to order a query by a date column to show the most recent entry at the top, but it wasn’t working because the date column was stored as a nvarchar instead of a datetime.
I tried various things like CONVERT…. and CAST…AS datetime, but for whatever reason I could not get this to work.
I got round this by doing some string concatenation:
SELECT * FROM tbl_articles
WHERE visible = 1
ORDER BY RIGHT(dateval,4)+SUBSTRING(dateval, 4, 2)+LEFT(dateval,2) ASC
The date was stored in the table as text like 22/10/2011, the above concatenating turns it into 20111022 which can easily be sorted in the proper order.
I know this is more than likely not the best way of doing it and should have persevered with the casts and converts but it works fine for the minimal amount of data I have in that table. No doubt I’ll have to revisit this if the number of records significantly increases.