Convert Month Number to Month Name Function in SQL

前端 未结 30 2056
予麋鹿
予麋鹿 2020-11-22 11:53

I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I a

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 12:52

    Starting with SQL Server 2012, you can use FORMAT and DATEFROMPARTS to solve this problem. (If you want month names from other cultures, change: en-US)

    select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')
    

    If you want a three-letter month:

    select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMM', 'en-US')
    

    If you really want to, you can create a function for this:

    CREATE FUNCTION fn_month_num_to_name
    (
        @month_num tinyint
    )
    RETURNS varchar(20)
    AS
    BEGIN
        RETURN FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')
    END
    

提交回复
热议问题