简体   繁体   中英

SAS Macro in macro

I have one question regaring %macro. Can I set %macro in another %macro?

Short example - "picture" of situation:

%macro Tier_1();

   %do Iter = 1 to &i;

       %macro Tier_2()

       proc sql noprint;
         select
         1*&Iter  into :var
       from work._PRODSAVAIL
       ;quit;

        %put &var;

       %mend;
       %Tier_2();
  %end;

%mend;
%Tier_1();

The answer to your question is "yes, it is possible." But it's poor style. The identical results from above will occur if you simply move the macro definition for %Tier_2 outside of macro Tier_1, but leave the call inside it.

%macro tier_1();

  ... 

  %Tier_2();
%mend tier_1();

%macro tier_2();
  ...
%mend tier_2;

%tier_1();

As you see above, you don't even have to order them in a particular way - as long as both are compiled before the execution of the macro it will work fine.

The only time it would make sense to put a macro definition inside another macro definition would be if the outer macro modified the inner macro in some way , and so it was necessary to re-compile the inner macro each time the outer macro executes.

While that's a theoretical use case, I don't think it's one you are likely to encounter in practice; there are lots of other ways to modify things without actually modifying the macro code itself, and as such it's considered poor programming style and should be avoided. You're adding (minimal, but some) overhead for no real benefit, and making it harder to understand the code.

The definitions are NOT logically nested. There is just a flat space of macro names. If you define the same %submacro inside of %macroA and %macroB there will only be one %submacro , which ever definition ran most recently.

You can nest macro CALLS (call a macro as part of a macro) but nesting the source code of the macro definitions is not a good idea. You can do it, but it will just confuse you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM