Sql 函数将日期显示为YYYY-MMM
正如标题所述,我正在尝试创建一个小函数,以获取数据库中已有的日期值,并将其显示为YYYY-MMM(例如:2013年11月)。SQL Server。我尝试了DatePart,但一次只需要一个part参数(不能执行YYYY-MMM)。是否有任何建议将其保留为功能Sql 函数将日期显示为YYYY-MMM,sql,sql-server,user-defined-functions,date-formatting,scalar,Sql,Sql Server,User Defined Functions,Date Formatting,Scalar,正如标题所述,我正在尝试创建一个小函数,以获取数据库中已有的日期值,并将其显示为YYYY-MMM(例如:2013年11月)。SQL Server。我尝试了DatePart,但一次只需要一个part参数(不能执行YYYY-MMM)。是否有任何建议将其保留为功能 Create function fnYearMonth (@InputDate date) returns date Begin Return DatePart(YYYY-MMM, @inputdate) End; Select hire
Create function fnYearMonth
(@InputDate date)
returns date
Begin
Return DatePart(YYYY-MMM, @inputdate)
End;
Select hiredate, dbo.fnYearMonth(hiredate) as ReviewDate
from employees
Order by ReviewDate
使用
结果:
2013年10月
编辑:
使用功能:
Create function fnYearMonth
(@InputDate date)
returns VARCHAR(16)
Begin
Return CAST(YEAR(@InputDate) AS CHAR(4)) + ' '+ DATENAME ( month , @InputDate )
End;
或
如果您不需要月份的全名。
返回日期
将必须更改以使其生效-日期就是日期就是日期。它没有格式。它只存储自某个特定纪元日期以来已发生的天数的一些内部表示。
Create function fnYearMonth
(@InputDate date)
returns nvarchar(8)
Begin
Return CAST(DatePart(YYYY, @InputDate) as nvarchar(4)) + '-' + CONVERT(nvarchar(3), datename(month, @InputDate))
End;
Create function fnYearMonth
(@InputDate date)
returns VARCHAR(16)
Begin
Return CAST(YEAR(@InputDate) AS CHAR(4)) + ' '+ DATENAME ( month , @InputDate )
End;
CAST(YEAR(@InputDate) AS CHAR(4)) + ' '+ LEFT(DATENAME ( MONTH , @InputDate ),3)