I am trying to convert a Datetime from 29/07/2011 00:00:00 this from this format to just 29/07/2011. I do this with a SELECT statement
SELECT CONVERT(nvarchar(10), thisDate, 103) As thisDate ... ORDER BY thisDate
This gives an order of something like this
01/08/2011
02/08/2011
05/06/2011
08/07/2011
14/07/2011
21/06/2010
21/07/2011
23/07/2011
24/07/2011
24/07/2011
However when I use 101
or 102
formatting the results are correct and the dates are ordered correctly.
You can order by field of type DATETIME. In you example you need to rename the alias:
SELECT CONVERT(nvarchar(10), thisDate, 103) As thatDate ... ORDER BY thisDate
Don't convert datetime to string - converting for display purpose should be done at client side, according to the client setup. For ordering the resultset you should use date field directly, no need to convert it, it would be just waste of resources.
The 102
style "works" because it formats date as "yy.mm.dd" which sorts "correctly" (can be ordered as string according the same rules as dates). So does 112
("yyyymmdd") and some others, but 101
shouldn't work as you expect (it's US format "mm/dd/yyyy").
Your solution doesn't work because SQL server is trying to sort based on a text string which gets sorted alphabetically, instead of sorting by date.
Try doing this to your query:
SELECT CONVERT(nvarchar(10), thisDate, 103) As newDate, thisDate
FROM YourTable
ORDER BY thisDate ASC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.