sql - Format varchar type and convert it to date variable -
i have varchar value in format “yyyymm-ll” where: yyyy 4 digit year; mm 2 digit month.ll 2 digit length of reporting period. number of whole months included in calculations (from first last day of each month).
my questions how use varchar value decide 2 variables:@first_date , @last_date.
example: 201409-06 scenario 6 months ending in september of 2014. range of calendar dates in scenario 04/01/2014 through 09/30/2014.
so how use t-sql find 2 dates @first_date : 04/01/2014 , @last_date: 09/30/2014.
any appreciated!
you can this:
select @firstdate = dateadd(month, 1 - cast(right('201409-06', 2) int), convert(date, left('201409-06', 6) + '01') ), @lastdate = dateadd(day, -1, dateadd(month, 1, convert(date, left('201409-06', 6) + '01') ) )
this parses string date arithmetic want. sql server recognizes string in form of "yyyymmdd" date, regardless of internationalization settings.
and sql fiddle.
Comments
Post a Comment