Search code examples
sasincludesas-macro

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.

Solution

  • 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;