Hello,
I have a small macro which conditionally executes code bases on state abbreviation. I want to execute some code for Oregon (State abbreviation OR). The code I am having trouble with is the following:
%MACRO Test(ST);
%IF &ST. = OR %THEN %DO;
%PUT State is Oregon.;
%END;
%ELSE %DO;
%PUT State is not Oregon.;
%END;
%MEND;
%Test(OR);
I think the issue is because OR is a keyword. The macro works fine for PA, or IN and so on but not for OR. Is there a quoting function or something I can use to overcome this issue? Thank you.
try:
%MACRO Test(ST);
%IF &ST. = "OR" %THEN %DO;
%PUT State is Oregon.;
%END;
%ELSE %DO;
%PUT State is not Oregon.;
%END;
%MEND;
%Test("PA");
A small tweak to the suggested solution: double quotes on both sides.
%if "&st." = "OR" %then %do;
Macro quoting functions could be used, but at least for this simple test the double quotes will work fine.
macro quoting to protect against finding a variable resolves to what looks like logic is straightforward in this case.
rather that quotes use the function %str()
%if %str(&st) EQ %str(OR) %then %do;
/* whatever you need to do for OR */
%end;
I was thinking that %STR(&ST) would not be the right function but it does work when the value of ST=OR. Guess I need to RTFM.
I think using and execution time function is safer.
I can't be giving data_null_; explanations I'm used to those flowing in the other direction!
here %str() is suitable because of the limited range of values that &ST might take - all state abbreviations. the time when extra protection is necessary occurs when the macro variable might contain special symbols not "protected" by %str(). These special symbols % and & would be well protected by%superq() but might need no more than %nrstr() - depending on the timing required for resolving values.
IN general defensive programming recommends %superq() as data_null; suggested here.
%Str() is adequate on this occasion because we know what range of values &ST will take.
The following code works:
%MACRO Test(ST);
%IF "&ST" = "OR" %THEN %DO;
%PUT State is Oregon.;
%END;
%ELSE %DO;
%PUT State is not Oregon.;
%END;
%MEND;
%Test(OR);
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Select SAS Training centers are offering in-person courses. View upcoming courses for: