Convert SQL Server Date to mm-yyyy

杀马特。学长 韩版系。学妹 提交于 2019-11-27 23:55:11

问题


I'm trying to convert my Date which is (eg. 2012-04-20 05:54:59) format in into mm-yyyy. I came across some solutions that says you would need to convert into varchar . Is there any way using the Convert function ?

Thanks :)


回答1:


You can use FORMAT function, available from SQL Server 2012 onwards:

DECLARE @myDate DATETIME = '2012-04-20 05:54:59'
SELECT FORMAT(@myDate, 'MM-yyyy') 

Output:

04-2012



回答2:


There might be a more graceful way to pull this off, but the below works.

Declare @dt datetime = GETDATE() 

SELECT LEFT('0' + CAST(MONTH(@dt) as varchar(2)),2)  + '-' + CAST(YEAR(@dt) as char(4))

btw my normal Date Conversion cheat sheet is here, but I'm not seeing MM-YYYY as one of the formats.




回答3:


  select [MM-YYYY] = right(convert(varchar(10),getdate(),105),7)




回答4:


As you are using SQL Server 2014, You can use FORMAT which is the best also you can apply this:

SELECT CONVERT(VARCHAR(2),MONTH(yourDateTimeField)) + '-' + 
       CONVERT(VARCHAR(4),YEAR(yourDateTimeField)) AS [MM-YYYY]
FROM yourTable
ORDER BY yourDateTimeField


来源:https://stackoverflow.com/questions/28842873/convert-sql-server-date-to-mm-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!