简体   繁体   中英

How to get end of month date from a “YearMonth” varchar column?

We have YearMonth VARCHAR(10) column and I am trying to create a date column which will give me last date of the month based on the YearMonth column.

For Example:
201612 - 12/31/2016
201602 - 02/29/2016
201702 - 02/28/2017

Assume your varchar is 201612

Select EOMonth(cast(YourVarchar+'01' as date))

Returns

2016-12-31

If you wanted the MM/DD/YYYY format

Select Convert(varchar(10),EOMonth(cast(YourVarchar+'01' as date)),101)

If you are using a version of SQL before 2012:

Add a month to the date with DATEADD, then subtract a day also with DATEADD

SELECT DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(DATETIME, '201612' + '01')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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