Convert Month Number to Month Name Function in SQL

前端 未结 30 1613
予麋鹿
予麋鹿 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:28

    A little hacky but should work:

    SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))
    
    0 讨论(0)
  • 2020-11-22 12:29

    Try this: SELECT MONTHNAME(concat('1970-',[Month int val],'-01'))

    For example- SELECT MONTHNAME(concat('1970-',4,'-01'))

    The answer is - April

    0 讨论(0)
  • 2020-11-22 12:30

    Use this statement for getting month name:

    DECLARE @date datetime
    SET @date='2015/1/4 00:00:00'
    
    SELECT CAST(DATENAME(month,@date )  AS CHAR(3))AS 'Month Name'
    

    This will give you short month name. Like this: Jan, Feb, Mar, etc.

    0 讨论(0)
  • 2020-11-22 12:30

    You can create a function like this to generate the Month and do SELECT dbo.fn_GetMonthFromDate(date_column) as Month FROM table_name

    
    /****** Object:  UserDefinedFunction [dbo].[fn_GetMonthFromDate]    Script Date: 11/16/2018 10:26:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[fn_GetMonthFromDate] 
    (@date datetime)
    RETURNS varchar(50)
    AS
    BEGIN
        DECLARE @monthPart int

    SET @monthPart = MONTH(@date) IF @monthPart = 1 BEGIN RETURN 'January' END ELSE IF @monthPart = 2 BEGIN RETURN 'February' END ELSE IF @monthPart = 3 BEGIN RETURN 'March' END ELSE IF @monthPart = 4 BEGIN RETURN 'April' END ELSE IF @monthPart = 5 BEGIN RETURN 'May' END ELSE IF @monthPart = 6 BEGIN RETURN 'June' END ELSE IF @monthPart = 7 BEGIN RETURN 'July' END ELSE IF @monthPart = 8 BEGIN RETURN 'August' END ELSE IF @monthPart = 9 BEGIN RETURN 'September' END ELSE IF @monthPart = 10 BEGIN RETURN 'October' END ELSE IF @monthPart = 11 BEGIN RETURN 'November' END ELSE IF @monthPart = 12 BEGIN RETURN 'December' END RETURN NULL END
    0 讨论(0)
  • 2020-11-22 12:33

    in addition to original

    SELECT DATENAME(m, str(2) + '/1/2011')

    you can do this

    SELECT DATENAME(m, str([column_name]) + '/1/2011')

    this way you get names for all rows in a table. where [column_name] represents a integer column containing numeric value 1 through 12

    2 represents any integer, by contact string i created a date where i can extract the month. '/1/2011' can be any date

    if you want to do this with variable

    DECLARE @integer int;
    
    SET @integer = 6;
    
    SELECT DATENAME(m, str(@integer) + '/1/2011')
    
    0 讨论(0)
  • 2020-11-22 12:33

    Use this statement to convert Month numeric value to Month name.

    SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))
    
    0 讨论(0)
提交回复
热议问题