Search notes:

SAS programming - macro statement: %if

%if %then

%macro tq84_if(val_one, val_two);

  %if &val_one gt &val_two %then %put "&val_one > &val_two";

%mend tq84_if;

%tq84_if(42, 10);
Github repository about-SAS, path: /macro-processor/statements/if/then.sas

%if %then %else

%macro tq84_if_then_else(val_one, val_two);

  %if &val_one gt &val_two
      %then %put "&val_one > &val_two";
      %else %put "&val_one <= &val_two";

%mend tq84_if_then_else;

%tq84_if_then_else(42, 10);
%tq84_if_then_else(42, 42);
%tq84_if_then_else(42, 99);
Github repository about-SAS, path: /macro-processor/statements/if/else.sas

%if %then %else %if %then

%macro num_to_foo_bar_baz(num);

  %if       &num eq 1 %then 'foo';
  %else %if &num eq 2 %then 'bar';
  %else                     'baz';

%mend num_to_foo_bar_baz;

%put %num_to_foo_bar_baz(1);
%put %num_to_foo_bar_baz(2);
%put %num_to_foo_bar_baz(3);
Github repository about-SAS, path: /macro-processor/statements/if/if_else-if_else.sas

%if %then %do

%macro greater(a, b);
  
  %if &a gt &b
    %then
      %do;
        %put a is greater than b;
        %put b is less than a;
      %end;
    %else
      %do;
        %put a is less or equal than b;
        %put b is greater or equal than a;
      %end;
       
%mend greater;

%greater(10, 20);
%greater(20, 20);
%greater(30, 20);
Github repository about-SAS, path: /macro-processor/statements/if/then-do_else-do.sas

Integer arithmetic via %eval

The %if statement uses the %eval function to evaluate its condition.
Since %eval is only capable of integer arithmetic, an %if statement cannot handle something like %if 5.3 + 2.1 > 4.9:
%macro tq84_if;

  %if 39 + 3 = 42
  %then %put indeed, 39 + 3 is 42;
  %else %put surprisingly, 39 + 3 is not 42;


  /* The following %if statement does not work; it
     will cause the following error message:
       ERROR: A character operand was found in the %EVAL
              function or %IF condition where a numeric
              operand is required.
              The condition was: 
                  38.9 + 3.1 = 42 
       ERROR: The macro TQ84_IF will stop executing.*/

  %if 38.9 + 3.1 = 42
  %then %put indeed, 38.9 + 3.1 is 42;
  %else %put surprisingly, 38.9 + 3.1 is not 42;

%mend tq84_if;
Github repository about-SAS, path: /macro-processor/statements/if/integer-arithmetic.sas

OR is possible

Alhtough %if uses %eval, it can handle or conditions:
%macro isFooBarOrBaz(txt);

  %if %upcase(&txt) eq FOO or
      %upcase(&txt) eq BAR or
      %upcase(&txt) eq BAZ %then

      yes

  %else

      no
  
%mend;

%put %isFooBarOrBaz(Bar);  /* yes */
%put %isFooBarOrBaz(xyz);  /* no  */
%put %isFooBarOrBaz(BAZ);  /* yes */
Github repository about-SAS, path: /macro-processor/statements/if/or.sas

See also

if
macro statements

Index