Convert Month Number to Month Name Function in SQL

2018-12-31 17:38发布

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 am trying to avoid a CASE statement, if possible.

30条回答
荒废的爱情
2楼-- · 2018-12-31 18:15

Use the Best way

Select DateName( month , DateAdd( month , @MonthNumber , -1 ))
查看更多
无与为乐者.
3楼-- · 2018-12-31 18:15
to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')

where V_MONTH_NUM is the month number

SELECT to_char(to_date(V_MONTH_NUM,'MM'),'MONTH')  from dual;
查看更多
孤独寂梦人
4楼-- · 2018-12-31 18:16

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

SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))
查看更多
一个人的天荒地老
5楼-- · 2018-12-31 18:16

Starting with SQL Server 2012, you can use FORMAT and DATEFROMPARTS to solve this problem.

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
查看更多
只靠听说
6楼-- · 2018-12-31 18:17

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                   |
查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 18:18

This one worked for me:

@MetricMonthNumber (some number)

SELECT 
(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName
FROM TableName

From a post above from @leoinfo and @Valentino Vranken. Just did a quick select and it works.

查看更多
登录 后发表回答