Search code examples
if-statementsasmacros

SAS how to use character variable in if statment


I want to use character variable for if statement comparison, however why SAS always trying to treat it as numeric?

let VAR = "apple"

other code...

%macro Exec_day1();
If &VAR. eq "apple" %then %do;
    %include "/code.sas";
%end;

%mend;
%Exec_day1();

ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was: &VAR. eq "apple"


Solution

  • Assuming that you actually had the % in the %IF then your code will work. Try this example.

    %let mvar = "apple" ;
    %if &mvar = "apple" %then %do;
      %put The value of MVAR is &mvar and that is the same as "apple".;
    %end;    
    

    But if you leave the quotes out of the value of MVAR

    %let mvar = apple ;
    

    Then they will not match.

    Most likely the issue is that you do not actually have a macro variable with that name. You can use the above example to generate such an error if you just add

    %symdel mvar ;
    

    right before the %IF statement.

    3    %if &mvar = "apple" %then %do;
    WARNING: Apparent symbolic reference MVAR not resolved.
    WARNING: Apparent symbolic reference MVAR not resolved.
    ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was:
           &mvar = "apple"
    ERROR: Skipping to next %END statement.
    4      %put The value of MVAR is &mvar and that is the same as "apple".;
    5    %end;
    

    Otherwise you might be seeing that error message from some other %IF statement. Perhaps one that was in the %INCLUDE file. Add the /SOURCE2 option to the %INCLUDE so that the lines of code read from that file will appear in the SAS log.

    %include "/code.sas" / source2;