Dirk Horsten
Dirk Horsten

Reputation: 3845

How to conditionally %include a *.sas file that defines a macro?

I use a macro in several SAS programs, so I defined it in a separate file /myFolder/myMacro.sas.

When running in batch, I want to use it this way: %include '/myFolder/myMacro.sas;'

When testing changes to the code in Enterprise Guide, I wan to edit and run /myFolder/myMacro.sas, then edit and run the programs that use it. How do I conditionally include the macro definitions?

%if &server = BATCH_SERVER %then %include '/myFolder/myMacro.sas;' does not work: The file is included anyway and the %if statement is applied to the comment on top of the file and results in

ERROR: Expected %DO not found.
ERROR: Skipping to next %END statement.

Upvotes: 0

Views: 542

Answers (2)

Dirk Horsten
Dirk Horsten

Reputation: 3845

As I suspected, the error occurs because the include file starts with comments, somthing like:

* MyMacro is written to do this and that *;
* ************************************** *;
%macro MyMacro;
    proc this;
    proc that;
    run;
%mend;

So after including the file, this becomes

%if &server = BATCH_SERVER %then * MyMacro is written to do this and that *;
* ************************************** *;
%macro MyMacro;
    proc this;
    proc that;
    run;
%mend;

which is invalid.

When working inside a macro: add %do; and %end;

As Allan suggested, it is sufficient to put the %inlcude between %do; and %end;

%if &server = BATCH_SERVER %then %do;
    %include '/myFolder/myMacro.sas;'
%end;

So after including the file, this becomes

%if &server = BATCH_SERVER %then %do;
    * MyMacro is written to do this and that *;
    * ************************************** *;
    %macro MyMacro;
        proc this;
        proc that;
        run;
    %mend;
%end;

which works.

When working in open code: use call execute

data _null_;
    if "&mode"="BATCH" then call execute ("%include /myFolder/myMacro.sas;");
run;
%DoIt;

Upvotes: 0

Allan Bowe
Allan Bowe

Reputation: 12701

Just use a %then %do

%let mode=BATCH;
filename mac1 temp;
filename mac2 temp;

data _null_;
  file mac1;
  put '%macro mac1;%put mac1;%mend;%mac1;';
data _null_;
  file mac2;
  put '%macro mac2;%put mac2;%mend;%mac2';
run;
%if &mode=BATCH %then %do;
  %inc mac2;
%end;
%else %do;
  %inc mac1;
%end;

Upvotes: 1

Related Questions