Testing for an empty parameter in a SAS Macro

天涯浪子 提交于 2019-12-01 09:17:47

For this answer I will cite Chang Chung's seminal paper, "Is This Macro Parameter Blank", as it is excellent and goes into great detail about your options here.

The "best" option follows (ie, using the recommended method from the paper above). Note the initial %test macro doesn't return any rows for the blank parameter, while the second %test2 does.

There are simpler ways to test for a macro parameter being blank that work in most cases, and read the paper for more details about the simpler options.

%macro test(parameter1= , parameter2=, sex=);
  DATA data_gender;
  SET sashelp.class(where=(sex="&sex."));
  RUN;
%mend;

%test(sex=M);
%test(sex=F);
%test(sex=);

%macro test2(parameter1= , parameter2=, sex=);
  DATA data_gender;
  SET sashelp.class(
    %if %sysevalf(%superq(sex) ne,boolean) %then %do;
        where=(sex="&sex.")
        %end;
    );
  RUN;
%mend;

%test2(sex=M);
%test2(sex=F);
%test2(sex=);

Agree with Joe's answer. One good point they make in the paper is they are testing for blank, and their test will return true whether a parameter is null or has blanks in it. Sometimes it is useful have a test that differentiates between a parameter that is null and one that has blanks. The paper mentions %length(%superq( )) as a possible test for null. For example below, this allows you to specify a blank value for sex, and get a different result than you do when sex is null.

data class;
  set sashelp.class;
  if _n_=1 then sex='';
run;

%macro test2(parameter1= , parameter2=, sex=);
  DATA data_gender;
  SET class(
            %if %length(%superq(sex)) %then %do;
              where=(sex="&sex.")
            %end;
           );
  RUN;
%mend;

%test2(sex=)
%test2(sex=%str( ))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!