Some SAS Macro code for detecting the presence or absence of a variable in a dataset
Published on 4th December 2013 Estimated Reading Time: 2 minutesRecently, I needed to put in place some code to detect the presence or absence of a variable in a dataset, and I chose SAS Macro programming as the way to do what I wanted. The logic was based on a SAS sample that achieved the same result in a data step and some code that I had for detecting the presence or absence of a dataset. Mixing the two together gave me something like the following:
%macro testvar(ds=,var=);
%let dsid=%sysfunc(open(&ds,in));
%let varexist=%sysfunc(varnum(&dsid,&var));
%if &dsid > 0 %then %let rc=%sysfunc(close(&dsid));
%if &varexist gt 0 %then %put Info: Variable &var is in the &ds dataset;
%else %put Info: Variable &var is not in the &ds dataset;
%mend testvar;
%testvar(ds=dataset,var=var);
What this does is open up a dataset and look for the variable number in the dataset. In datasets, variables are numbered from left to right with 1 for the first one, 2 for the second and so on. If the variable is not in the dataset, the result is 0 so you know that it is not there. All of this is what the VARNUM
SCL function within the SYSFUNC
macro function does. In the example, this resolves to %sysfunc(varnum(&dsid,var))
with no quotes around the variable name, akin to what you would do in data step programming. Once you have the variable number or 0, then you can put in place some conditional logic that makes use of the information, like what you see in the above simple example. Of course, that would be expanded to something more useful in real life, but I hope it helps to show you the possibilities here.