Search code examples
sassas-macro

Trying to write macro to read 24 months of data by yyyymmdd


I'm trying to write a macro to replace some current code. The current code is like this:

data _null_;
 call symput('as_of_date_nbr1', put(intnx('month', today(),-1, 'E'), yymmddn.));
run;
%put &as_of_date_nbr1 yields 20210831

There is a data_null for each of 30 months. That variable is then used in a data step where statement

where date = &as_of_date_nbr1

I want to write a macro where the variable as_of_date_nbr would take a macro variable from 1-30 and the intnx function would also take a macro variable from 1-30 So something like this if possible in a loop

data _null_;
call symput('as_of_date_nbr.&macvar, put(intnx('month,today(),-&macvar, 'E'), yyyymmddn.))

So far I'm not having any luck, any ideas would be appreciated.


Solution

  • First start by trying to create a data set with the 30 dates needed.

    data demo;
        do i=1 to 30;
            var_name=catt('month', put(i, z2. -l));
            var_value=intnx('month', today(), -1*i, 'e');
            format var_value yymmddn8.;
            output;
        end;
    run;
    

    Once you're sure that's correct, you can add a CALL SYMPTUX line to create the macro variables.

        call symputx(var_name, put(var_value, yymmddn8.), 'g');
    

    Depending on what you're doing overall, you may want to explore CALL EXECUTE. For examle if you were looping a macro with these values instead of call symputx you could use CALL EXECUTE() to just call the macro directly with the values instead.

    So if you had a macro called %filter like this:

    %macro filter(date_param);
       sas code
    %mend;
    

    You could call it instead as follows:

     call execute(catt('%filter_data(', put(var_value, yymmddn8.), ');'));
    

    All together it would be something like this:

    data demo;
        do i=1 to 30;
            var_name=catt('month', put(i, z2. -l));
            var_value=intnx('month', today(), -1*i, 'e');
            format var_value yymmddn8.;
            call symputx(var_name, put(var_value, yymmddn8.), 'g');
            *call execute(catt('%filter_data(', put(var_value, yymmddn8.), ');'));
            output;
        end;
    run;
    
    *check macro variables created properly;
    %put &month01.;
    %put &month15.;
    %put &month30.;