Convert month name to month number in SQL Server

后端 未结 13 1233
情话喂你
情话喂你 2020-12-01 13:57

In T-SQL what is the best way to convert a month name into a number?

E.g:

\'January\' -> 1
\'February\' -> 2
\'March\' -> 3
相关标签:
13条回答
  • 2020-12-01 14:45

    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
    
    0 讨论(0)
  • 2020-12-01 14:46

    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
    
    0 讨论(0)
  • 2020-12-01 14:47

    How about this:

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

    Would return 3.

    0 讨论(0)
  • 2020-12-01 14:50

    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
    
    0 讨论(0)
  • 2020-12-01 14:52

    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 
    
    0 讨论(0)
  • 2020-12-01 15:02

    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
    
    0 讨论(0)
提交回复
热议问题