Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert month name to month number in SQL Server

Tags:

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?

like image 317
Gary Barrett Avatar asked Nov 29 '11 16:11

Gary Barrett


People also ask

How do I get the number of months in SQL?

The MONTH() function returns the month part for a specified date (a number from 1 to 12).

How do I convert month number to month name?

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.

How do I sort by month name in SQL?

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.


2 Answers

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 
like image 113
Ric Avatar answered Sep 19 '22 14:09

Ric


How about this:

SELECT MONTH('March' + ' 1 2014')  

Would return 3.

like image 20
Sunil Johnson Avatar answered Sep 18 '22 14:09

Sunil Johnson