简体   繁体   English

将字符串YYYY-MM转换为日期YYYY-MM-DD

[英]converting String YYYY-MM to Date YYYY-MM-DD

I have a set of data below and they are all in string. 我在下面有一组数据,它们都是字符串。

EndDate
--------
2017-04

2017-02
2017-01
2017-03

2017-06

I would like to add the last date of the month into it. 我想添加一个月的最后一个日期。

EndDate
--------
2017-04-30

2017-02-28
2017-01-31
2017-03-31

2017-06-30

I'm thinking to convert them to date first and use EOMONTH syntax to give the last date of the month. 我正在考虑先将它们转换为日期,然后使用EOMONTH语法给出该月的最后日期。 However I have tried to convert the data to date using convert(datetime, EndDate) and it fails. 但是,我尝试使用convert(datetime, EndDate)将数据convert(datetime, EndDate)但是它失败了。

I tried a the syntax below from a post in stackoverflow however it gives me error message as well. 我从stackoverflow中的帖子尝试了以下语法,但是它也给我错误消息。

EOMONTH(CONVERT(VARCHAR(max),CAST(EndDate + '01' AS DATETIME),120))

FYI, the blank value should remain in the column. 仅供参考,空白值应保留在该列中。

I'm using SQL Server 2012 我正在使用SQL Server 2012

Thanks all for your help. 感谢你的帮助。

You were close! 你近了!

SELECT EOMONTH(TRY_CONVERT(date, EndDate + '-01', 120)) FROM ...

The date style 120 is yyyy-mm-dd, but you were creating a value that was yyyy-mmdd. 日期样式120为yyyy-mm-dd,但是您创建的值为yyyy-mmdd。 Also, you were passing a varchar into EOMONTH when you should just give it a date parameter. 另外,您应该在给varchar一个date参数时将其传递给EOMONTH

我认为应该这样做:

CASE WHEN ISNULL(EndDate, '') <> '' THEN EOMONTH(CAST(EndDate + '-01' AS DATETIME)) ELSE EndDate END 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM