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:19

A little hacky but should work:

SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))
查看更多
唯独是你
3楼-- · 2018-12-31 18:19
SELECT DATENAME(month, GETDATE()) AS 'Month Name'
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 18:19

In some locales like Hebrew, there are leap months dependant upon the year so to avoid errors in such locales you might consider the following solution:

SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(@month, 2), ' ', '0') + '01')     
查看更多
只若初见
5楼-- · 2018-12-31 18:20

You can use the convert functin as below

CONVERT(VARCHAR(3), DATENAME(MM, GETDATE()), 100)
查看更多
步步皆殇っ
6楼-- · 2018-12-31 18:20

Working for me

SELECT MONTHNAME(<fieldname>) AS "Month Name" FROM <tablename> WHERE <condition>
查看更多
伤终究还是伤i
7楼-- · 2018-12-31 18:21

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.

查看更多
登录 后发表回答