我将月份存储在SQL Server中为1,2,3,4,…12。我想把它们显示为一月,二月等。在SQL Server中有一个函数像MonthName(1) = 1月?如果可能的话,我尽量避免使用CASE语句。


当前回答

你可以这样得到日期。 -用户表

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

您可以像这样获得monthname

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

输出

+-----------+-------------------------------+
| year(created_at) | monthname(created_at)  |
+-----------+-------------------------------+
|      2017        | september              |
|      2017        | june                   |

其他回答

SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))
Declare @MonthNumber int
SET @MonthNumber=DatePart(Month,GETDATE())
Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )

解释:

第一次声明变量月号 获取DatePart的当前月份,返回月份号 第三次查询返回月份名称

在希伯来语等一些语言环境中,闰月取决于年份,因此为了避免在这些语言环境中出现错误,您可以考虑以下解决方案:

SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(@month, 2), ' ', '0') + '01')     
SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (@intMonth * 4) - 3, 3)

这个对我很有用:

@MetricMonthNumber (some number)

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

上面的帖子来自@leoinfo和@Valentino Vranken。刚刚做了一个快速选择,它工作。