Convert Month Number to Month Name Function in SQL

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

    Just subtract the current month from today's date, then add back your month number. Then use the datename function to give the full name all in 1 line.

    print datename(month,dateadd(month,-month(getdate()) + 9,getdate()))
    
    0 讨论(0)
  • 2020-11-22 12:33

    To convert month number to month name, try the below

    declare @month smallint = 1
    select DateName(mm,DATEADD(mm,@month - 1,0))
    
    0 讨论(0)
  • 2020-11-22 12:35

    I think this is the best way to get the month name when you have the month number

    Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
    

    Or

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

    You can use the convert functin as below

    CONVERT(VARCHAR(3), DATENAME(MM, GETDATE()), 100)
    
    0 讨论(0)
  • 2020-11-22 12:36

    You can use the inbuilt CONVERT function

    select CONVERT(varchar(3), Date, 100)  as Month from MyTable.
    

    This will display first 3 characters of month (JAN,FEB etc..)

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

    you can get the date like this. eg:- Users table

    id name created_at
    1  abc  2017-09-16
    2  xyz  2017-06-10
    

    you can get the monthname like this

    select year(created_at), monthname(created_at) from users;
    

    output

    +-----------+-------------------------------+
    | year(created_at) | monthname(created_at)  |
    +-----------+-------------------------------+
    |      2017        | september              |
    |      2017        | june                   |
    
    0 讨论(0)
提交回复
热议问题