This article explains how to distinguish a null (empty) macro variable from a macro variable containing a period, and how to perform these tests correctly.
%put The variable contains something (LENGTH > 0).;
4
5
%END;
6
Warning: If %let a = .;, then %length(&a) is 1. The test above will therefore consider that the variable is not empty.
Method 2: Direct comparison
Another common method is to compare the variable to an empty string.
%if &maVar = %then %do;
%put The variable is empty.;
%end;
1
%IF &maVar = %THEN %DO;
2
3
%put The variable is empty.;
4
5
%END;
6
Note: This method is sometimes less readable than using %length, but it is functional.
Common syntax errors to avoid
When writing these conditions, pay attention to the structure of your %if / %then / %else blocks.
The semicolon error after %else
A classic mistake is to place a semicolon immediately after the %else, which terminates the statement prematurely.
Note : Incorrect:
/* The semicolon after %else prevents the execution of the next block */
%if %length(&a) %then %do;
%put Exists;
%end;
%else;
%put Does not exist;
1
/* The semicolon after %else prevents the execution of the next block */
2
%IF %LENGTH(&a) %THEN %DO;
3
%put Exists;
4
%END;
5
%ELSE;
6
%put Does not exist;
Note : Correct:
%if %length(&a) %then %do;
%put Exists;
%end;
%else %do;
%put Does not exist;
%end;
1
%IF %LENGTH(&a) %THEN %DO;
2
%put Exists;
3
%END;
4
%ELSE %DO;
5
%put Does not exist;
6
%END;
The macro language manipulates text.
A period (.) is a character, not a missing value in the macro sense.
Use %if %length(&var) = 0 to test for a null (empty) value.
To delve deeper into the subject of missing and logical values in macros, the works of Chung and King on the subject are solid technical references.
Important Disclaimer
The codes and examples provided on WeAreCAS.eu are for educational purposes. It is imperative not to blindly copy-paste them into your production environments. The best approach is to understand the logic before applying it. We strongly recommend testing these scripts in a test environment (Sandbox/Dev). WeAreCAS accepts no responsibility for any impact or data loss on your systems.
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration. WeAreCAS is an independent community site and is not affiliated with SAS Institute Inc.
This site uses technical and analytical cookies to improve your experience.
Read more.