Search code examples
sassas-macro

proq sql macro; loop through list


I have a macro that looks for variable names in a given dataset. If the variable name the macro is looking for is missing, the missing variable's name gets added to a table:

%macro miss(ds, var);
    %local rc dsid result;
    %let dsid=%sysfunc(open(&ds));
    %if %sysfunc(varnum(&dsid,&var)) > 0 %then %do;
        %put &var present;
    %end;
    %else %do;
        insert into work.compare(missing) values("&var")
    %end;
%mend;

proc datasets library=work nolist nodetails;
    delete compare;
run;

proc sql;
    create table work.compare (missing char(15));
%miss(ctr.panup_in, u_name);
quit;

proc print noobs data=work.compare;
run;

This check needs to be run for 55 different variable names. At the moment, I just have every single one listed as a

%miss(ctr.panup_in, varname);

line.

For practical reasons, I would like to specify the list of variables as a list, eg %let dictionary=var1 var2 var3 etc. My struggle right now is to find a way for the macro to loop through a variable list. Everything I've tried so far leads to a "Stament is not valid" error for the

insert into work.compare(missing) values("&var")

command.

Does anyone have any advice on how to do this?


Solution

  • This Loops thoough a set of variables where the variables are separated by "|". Any other delimiter can be used and specified in the scan function as well.

    %macro loop(varlist);
    %let i=1;
    %do %while (%scan(&varlist, &i, |) ^=%str());
    %let var=%scan(&varlist, &i, |); 
    %put &var;
    
    *rest of SAS code goes here;
    
    *Increment counter;
    %let i=%eval(&i+1);
    %end;
    %mend;
    %let temp=a|b|c|d|e;
    %loop(&temp);