Home > Blockchain >  'January-2016' string date in SQL Server - increment by one month
'January-2016' string date in SQL Server - increment by one month

Time:03-22

January-2016
August-2017
November-2018
January-2018
August-2018
November-2018

This is my date format how to increment month by 1 ?

CodePudding user response:

DECLARE @Str VARCHAR(20) = 'January-2016'

SELECT FORMAT(DATEADD(MONTH , 1 , 
                    DATEFROMPARTS(RIGHT(@Str, 4) ,  DATEPART (MM, REPLACE(@Str , '-' , ' 01 ')) , 01)
                    ) 
            , 'MMMM-yyyy')

Result: February-2016

CodePudding user response:

You can just replace the dash with ' 1 ', as long as you explicitly use English:

SET LANGUAGE us_english;

DECLARE @s varchar(67) = 'January-2016';  

SELECT TRY_CONVERT(date, REPLACE(@s, '-', ' 1 '));

So then add a month:

SELECT DATEADD(MONTH, 1, <try_convert expression>);
  • Related