SAS Tip: Check if a variable exists in a dataset (Daily tip for 2025-Jan-22)


Have you ever needed to know if a given variable is in a SAS data set? This macro returns 1 if a variable exists in a data set, and 0 if not.

%macro VarExist(ds, var);
    %local rc dsid result;
    %let dsid = %sysfunc(open(&ds));
 
    %if %sysfunc(varnum(&dsid, &var)) > 0 %then %do;
        %let result = 1;
        %put NOTE: Var &var exists in &ds;
    %end;
    %else %do;
        %let result = 0;
        %put NOTE: Var &var not exists in &ds;
    %end;
 
    %let rc = %sysfunc(close(&dsid));
    &result
%mend VarExist;
 
/* Usage */
%put %VarExist(sashelp.class, name);
%put %VarExist(sashelp.class, aaa);
This tip was originally posted by Adrien Vallee on sasCommunity.org.

READ this complete tip   Visit a random SAS tip

Start a topic
About these Tips
A "SAS tip" is a basic unit of information exchange between SAS users. The tips on this board come from sasCommunity.org, from SAS user conferences, from SAS blogs, and from freelance contributions from SAS users like you. We hope that you're able to always learn something new here!


» How you can contribute


Tip-o-meter: 63 tips