Convert month name to month number in SQL Server

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

    You can create a function and then refer to it in the select statement. The function may look similar to this:

    if OBJECT_ID('fn_month_name_to_number', 'IF') is not null
    drop function fn_month_name_to_number
    go
    create function fn_month_name_to_number (@monthname varchar(25))
    returns int as
    begin
    declare @monthno as int;
    select @monthno =
    case @monthname
    when 'January' then 1
    when 'February' then 2
    when 'March' then 3
    when 'April' then 4
    when 'May' then 5
    when 'June' then 6
    when 'July' then 7
    when 'August' then 8
    when 'September' then 9
    when 'October' then 10
    when 'November' then 11
    when 'December' then 12
    end
    return @monthno
    end
    

    Then you can query it.

    select fn_month_name_to_number ('February') as month_no
    

    This query will return 2 as month number. You can pass values from a column as parameters to the function.

    select fn_month_name_to_number (*columnname*) as month_no from *tablename*
    

    Have a good day!

提交回复
热议问题