In T-SQL what is the best way to convert a month name into a number?
E.g:
\'January\' -> 1
\'February\' -> 2
\'March\' -> 3
Its quit simple, Take the first 3 digits of the month name and use this formula.
Select charindex('DEC','JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC')/4+1
I know this may be a bit too late but the most efficient way of doing this through a CTE as follows:
WITH Months AS
(
SELECT 1 x
UNION all
SELECT x + 1
FROM Months
WHERE x < 12
)
SELECT x AS MonthNumber, DateName( month , DateAdd( month , x , -1 )) AS MonthName FROM Months
How about this:
SELECT MONTH('March' + ' 1 2014')
Would return 3
.
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
I think you may even have a separate table like a monthdetails (Monthno int, monthnames char(15))
and include values:
1 January
2 February
.... and so on, and then join this table with your existing table in the monthnames
column
SELECT t1.*,t2.Monthno from table1
left outer join monthdetails t2
on t1.monthname=t2.monthnames
order by t2.Monthno
You can use below code
DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`
SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric