sql server - Get previous month in SQL when given a varchar -
if have varchar
looks following:
'201503'
how similiar varchar
representation of previous month? e,g, '201502'
? if month falls on january i.e. '201501'
should '201412'
some appreciated :)
try this:
declare @dt varchar(8) = '201501' select left(convert(varchar(8), dateadd(m, -1, @dt + '01'), 112), 6)
output:
201412
using dateadd can calculate previous month. function conveniently accepts string argument. convert used convert result yyyymmdd
format.
Comments
Post a Comment