Convert Month Number to Month Name Function in SQL

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

    Here is my solution using some information from others to solve a problem.

    datename(month,dateadd(month,datepart(month,Help_HelpMain.Ticket_Closed_Date),-1)) as monthname
    
    0 讨论(0)
  • 2020-11-22 12:38

    There is no system defined function in SQL server. But you can create your own user-defined function- a scalar function. You would find scalar functions in the Object Explorer for your database: Programmability->Functions->Scalar-valued Functions. Below, I use a table variable to bring it all together.

    --Create the user-defined function
    CREATE FUNCTION getmonth (@num int)
    RETURNS varchar(9) --since 'September' is the longest string, length 9
    AS
    BEGIN
    
    DECLARE @intMonth Table (num int PRIMARY KEY IDENTITY(1,1), month varchar(9))
    
    INSERT INTO @intMonth VALUES ('January'), ('February'), ('March'), ('April'), ('May')
                               , ('June'), ('July'), ('August') ,('September'), ('October')
                               , ('November'), ('December')
    
    RETURN (SELECT I.month
            FROM @intMonth I
            WHERE I.num = @num)
    END
    GO
    
    --Use the function for various months
    SELECT dbo.getmonth(4) AS [Month]
    SELECT dbo.getmonth(5) AS [Month]
    SELECT dbo.getmonth(6) AS [Month]
    
    0 讨论(0)
  • 2020-11-22 12:39

    Use the Best way

    Select DateName( month , DateAdd( month , @MonthNumber , -1 ))
    
    0 讨论(0)
  • 2020-11-22 12:39

    Sure this will work

    select datename(M,GETDATE())
    
    0 讨论(0)
  • 2020-11-22 12:39

    i think this is enough to get month name when u have date.

    SELECT DATENAME(month ,GETDATE())
    
    0 讨论(0)
  • 2020-11-22 12:40

    The following works for me:

    CAST(GETDATE() AS CHAR(3))
    
    0 讨论(0)
提交回复
热议问题