Convert month name to month number in SQL Server

后端 未结 13 1371
情话喂你
情话喂你 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: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
    

提交回复
热议问题