In T-SQL what is the best way to convert a month name into a number?
E.g:
'January' -> 1 'February' -> 2 'March' -> 3
Etc.
Are there any built in functions that can do this?
The MONTH() function returns the month part for a specified date (a number from 1 to 12).
An alternative way to get a month number from an Excel date is using the TEXT function: =TEXT(A2, "m") - returns a month number without a leading zero, as 1 - 12. =TEXT(A2,"mm") - returns a month number with a leading zero, as 01 - 12.
To order by month, create a date with this month. To do this, use the STR_TO_DATE() function. If you have a date stored as a string in the ' Year Month Day ' format, you can cast it to a date using STR_TO_DATE(date_string, '%Y %M %d') . The CONCAT() function combines all the arguments into one string.
How about this?
select DATEPART(MM,'january 01 2011') -- returns 1 select DATEPART(MM,'march 01 2011') -- returns 3 select DATEPART(MM,'august 01 2011') -- returns 8
How about this:
SELECT MONTH('March' + ' 1 2014')
Would return 3
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With