Reputation: 507
I need to update a dataset mylib.dt_old using the dataset dt_new, but I want to first check if it actually exists, otherwise I would get an error. In case it does not exist, I just want to create a dataset mylib.dt_old that stores the information contained in dt_new. I tried the following:
if (exist(mylib.dt_old))
then do;
data mylib.dt_old;
update mylib.dt_old dt_new;
by date var1 var2;
run;
end;
else do;
data mylib.dt_old; set dt_new;
run;
end;
However I get the error, when mylib.dt_old does not exist
ERROR: File MYLIB.DT_OLD.DATA does not exist.
and sas goes on actually executing the else statement (creates dt_old copying dt_new).
Instead if dt_old does exist I get
if (exist(mylib.dt_old))
--
180
ERROR 180-322: Statement is not valid or it is used out of proper order.
What am I doing wrong? PS: I am a beginner in SAS.
Upvotes: 1
Views: 2055
Reputation: 1807
What you're trying to do would actually qualify as macro programming in SAS, which is sometimes considered an "advanced" topic.
The normal if-then control logic you're using is what SAS considers data-step code, i.e. it's only valid in the data step. But there is a "macro" language that looks similar, but is distinguished by %
prefixes. Here's how your modified code might look:
%macro updater();
%if %sysfunc(exist(mylib.dt_old))
%then %do;
data mylib.dt_old;
update mylib.dt_old dt_new;
by date var1 var2;
run;
%end;
%else %do;
data mylib.dt_old;
set dt_new;
run;
%end;
%mend updater;
%updater()
While this example is sort-of straightforward, the SAS macro language is frequently counterintuitive (to me at least). If you're a beginner it might be a good idea to find and read an "into to SAS macros" online.
Upvotes: 3