Search code examples
if-statementsassas-macromacro-variable

Conditionally set a %let statement SAS


I was hoping someone could help with %if %then statements in SAS.

I want to conditionally set a macro variable so I was trying to do it this way:

%if &stress_test. = "Y" %then %let CURR_BOE = &BOE_ST.;
%if &stress_test. = "N" %then %let CURR_BOE = 0.0525;

Where &stress_test. is a macro variable already set. And &BOE_ST is a macro variable already set.


Solution

  • When you do %if-%then-%else Macro logic in open code, there are restrictions. See the blog post Using %IF-%THEN-%ELSE in SAS programs.

    1. The %if-%then must be followed by a %do-%end block for the statements that you want to conditionally execute.
    2. Nesting is not allowed.

    Since you have to consecutive %if statements in your code with no %do block following it, SAS interprets this as nesting and both restrictions are violated.

    This gives an error:

    %let stress_test = N;
    
    %if &stress_test. = Y %then %let CURR_BOE = 1;
    %if &stress_test. = N %then %let CURR_BOE = 2;
    
    %put &=CURR_BOE.;
    

    This does not give an error

    %let stress_test = N;
    
    %if &stress_test. = Y %then %do;
       %let CURR_BOE = 1;
    %end;
    %else %do;
       %let CURR_BOE = 2;
    %end;
    
    %put &=CURR_BOE.;
    

    Also, you could just wrap the whole thing into a macro and call that. Then you do not have the two restrictions mentioned.

    %macro m;
    
    %let stress_test = N;
    
    %if &stress_test. = Y %then %let CURR_BOE = 1;
    %if &stress_test. = N %then %let CURR_BOE = 2;
    
    %put &=CURR_BOE.;
    
    %mend m;
    
    %m