Iterate date in loop in SAS

Viewed 23

need help on one query , I have to iterate date in do loop that is in format of yymmd6.(202112) so that once the month reach to 12 then its automatically change to next year first month.

///// code////////

%let startmo=202010 ;
%let endmo= 202102;
%macro test;
%do month= &startmo %to &endmo;
  Data ABC_&month;
  Set test&month;
  X=&month ;
  %end;
  Run; 
%mend;
%test;

////////// Output should be 5 dataset as

ABC_202010
ABC_202011
ABC_202012
ABC_202101
ABC_20210

I need macro variable month to be resolved 202101 once it reached to 202012

2 Answers

Those are not actual DATE values. Just strings that you have imposed your own interpretation on so that they LOOK like dates to you.

Use date values instead and then it is easy to generate strings in the style you need by using a FORMAt.

%macro test(startmo,endmo);
  %local offset month month_string;
  %do offset = 0 to %sysfunc(intck(month,&startmo,&endmo));
    %let month=%sysfunc(intnx(month,&startmo,&offset));
    %let month_string=%sysfunc(putn(&month,yymmn6.));
data ABC_&month_string;
  set test&month_string;
  X=&month ;
  format X monyy7.;
run; 
  %end;
%mend;

%test(startmo='01OCT2020'd , endmo='01FEB2021'd)

And if you need to convert one of those strings into a date value use an INFORMAT.

%let date=%sysfunc(inputn(202010,yymmn6.));

I would prefer to use a do while loop. check whether the last 2 characters are 12, if so, change the month part to 01.

code

%let startmo=202010 ;
%let endmo= 202102;
%macro test;
  %do %while(&startmo <= &endmo);
    Data ABC_&startmo;
    Set test&startmo;
    X=&startmo ;
    Run;
  %end;
  %let mon = %substr(&startmo, 5, 2);
  %let yr = %substr(&startmo, 1, 4);
  %if &mon = 12 %then %do;
    %let m = 01;
    %let startmo = %sysfunc(cat(%eval(&yr + 1), &m));
  %end;
  %else %do;
    %let startmo = %eval(&startmo + 1);
  %end;
%mend;
%test;
Related