In this example page, I will demonstrate how to check if a SAS data set exists in a library or not. There are dozens of ways to do this. The most common is to use the Exist Function. Either in a macro, directly in a SAS Data Step or in open code. I will show small examples of all three.
In the examples, I look for the data set a below.
data a; a=1; run;
The Exist Function in the Data Step
First, let us see a simple example of how to check if the SAS data set a from above exists in the work library from the Data Step. Below, I use the Exist Function to check whether the data set is in the work library or not. If it is, I put “It’s there!” in the log. If it is not, I put “It’s not there!” in the log.
data _null_; if exist("a") then put "It's there!"; else put "It's not there!"; run;
A SAS Macro Example
Since you will rarely check if a SAS data set exists within the data step, we usually need to do so before we actually read the data. Therefore, it is wuite common to use macro logic to do so. Below, you can see a simple macro that takes a data set name as argument. Since I am in the macro environment and still want to call the Exist Function, I wrap the function in %sysfunc logic. Otherwise, the code below does the same thing as above.
%macro check(ds); %if %sysfunc(exist(&ds.)) %then %do; %put Its There!; %end; %else %do; %put Its Not There!; %end; %mend check; %check(a);
Open Code Example
From SAS 9.4M5, I can do the same thing as above in open code. This means that I do not have to wrap the code in a macro first. I can conditionally execute code depending on the existence of the data set I look for. This is a very useful feature. Both when you want to take different actions depending on the existence of the data set or in debugging.
%if %sysfunc(exist(work.a)) %then %do; %put Its There!; %end; %else %do; %put Its Not There!; %end;
On this example page, I demonstrate small code snippets that let you check if a SAS data set exists in a library or not. Obviously the code example here are ment as templates as you would usually write more complex logic depending on the outcode of the Exist Function. We see three different ways of checking. From the Data Step, in a macro call and conditional logic in open code. The last one requires SAS 9.4M5.
You can download the entire code from this example here.