sassas-macroproc-sql

How to create looping macro in SAS/ Proc SQL


I need to write code that performs the same action over and over, but using a different macro variable name each time. I've done this before, but can't quite remember the syntax.

Summary: I need to run the same code using multiple file inputs - all of the input files have a standardized name, with only the term name changed. I need the output file names to be organized in the same standard.

This is what I've come up with but it's not working. I don't get any errors in the log, it looks like it has run just fine, but there's no output:

%macro term;

proc sql;
create table work.output_&term. as
select distinct id, enrl_status 
from work.input_&term.
;
quit;

%mend term;

%let term=Fal22;
%let term=Spr22;

Solution

  • You need to define the macro to take a parameter. Since you seem to want to use TERM as the name of the macro variable let's use a different name for the name of the macro itself (they don't have to be different, but it will make it less confusing for humans).

    %macro extract(term);
    proc sql;
    create table work.output_&term. as
    select distinct id, enrl_status 
    from work.input_&term.
    ;
    quit;  
    %mend extract;     
    

    Then you can call the macro passing in different values for the parameter.

    %extract(term=Fal22)
    %extract(term=Spr22)