I have a complex sql query given to me by my colleague. I want to get one column in MMYYYY format. How can I achieve it? Following is the column part in query (the query is too long. so I am pasting only the column part).
CASE
WHEN len(datepart (WEEK, cast(cast(month(from_date) AS VARCHAR(2)) + '/' + cast(xx.day_val AS VARCHAR(2)) + '/' + cast(year(from_date) AS VARCHAR(4)) AS DATETIME))) = 1
THEN '0' + datepart (WEEK, cast(cast(month(from_date) AS VARCHAR(2)) + '/' + cast(xx.day_val AS VARCHAR(2)) + '/' + cast(year(from_date) AS VARCHAR(4)) AS DATETIME))
ELSE datepart (WEEK, cast(cast(month(from_date) AS VARCHAR(2)) + '/' + cast(xx.day_val AS VARCHAR(2)) + '/' + cast(year(from_date) AS VARCHAR(4)) AS DATETIME))
END AS week_number
You can only retain date in specific format if you store the date as a string (char/varchar) not as datetime / date.
To display date / datetime in a specific format, you need to use CONVERT or CAST:
SELECT CONVERT(varchar,CONVERT(datetime, ‘2010-03’), 103)
— 03/2010
Reference: http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes (i hope that this will answer your question)
Regards,
Nicholas