Thursday, October 8, 2015
SAS: Drop variable if it exists
* =============================================================== ;
* M A C R O D R O P _ V A R _ I F _ E X I S T S
* =============================================================== ;
%macro drop_var_if_exists(SASFILE=,VAR=);
%* See also http://sasrunner.blogspot.com/2009/09/check-variable-exist-in-data-step-run.html;
data _null_;
dsid = open("&SASFILE");
call symput("var_exists", varnum(dsid, "&VAR"));
rc = close(dsid);
run;
%if (&var_exists eq 0) %then %do;
%put Variable &VAR does not exist in &SASFILE ;
%end;
%else %do;
proc sql noprint;
alter table &SASFILE drop &VAR;
quit;
run;
%put Variable &VAR was dropped from file &SASFILE ;
%end;
%mend drop_var_if_exists;
* =============================================================== ;
* T E S T M A C R O D R O P _ V A R _ I F _ E X I S T S
* =============================================================== ;
* Create test dataset;
data work.mactest;
set sashelp.class (obs=10);
run;
title "Before drops";
proc print data=work.mactest;
run;
title;
%drop_var_if_exists(SASFILE=work.mactest, VAR=name);
%drop_var_if_exists(SASFILE=work.mactest, VAR=xyz);
%drop_var_if_exists(SASFILE=work.mactest, VAR=age);
title "After drops";
proc print data=work.mactest;
run;
title;
* Done ;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment