Home » How to Check if Dataset Exists in SAS (With Example)

How to Check if Dataset Exists in SAS (With Example)

by Tutor Aspire

You can use the following macro in SAS to quickly check if a dataset exists:

%macro check_exists(data);
   %if %sysfunc(exist(&data.)) %then %do;
      %put Dataset Exists;
   %end;
   %else %do;
      %put Dataset Does Not Exist;
   %end;
%mend check_exists;

When you run this macro, it will return “Dataset Exists” if a dataset exists.

Otherwise, it will return “Does Not Exist.”

The following example shows how to use this macro in practice.

Example: Check if Dataset Exists in SAS

Suppose we create the following dataset in SAS called data1:

/*create dataset*/
data data1;
    input hours score;
    datalines;
1 64
2 66
4 76
5 73
5 74
6 81
6 83
7 82
8 80
10 88
;
run;

/*view dataset*/
proc print data=data1;

We can define the following macro to check if a dataset exists:

%macro check_exists(data);
   %if %sysfunc(exist(&data.)) %then %do;
      %put Dataset Exists;
   %end;
   %else %do;
      %put Dataset Does Not Exist;
   %end;
%mend check_exists;

We can then run this macro to check if the dataset called data1 exists:

/*check if dataset called data1 exists*/
%check_exists(data1);

When we view the log, we can see that the macro returns Does Exist since data1 does indeed exist:

Now suppose we also run the macro to check if a dataset called data2 exists:

/*check if dataset called data2 exists*/
%check_exists(data2);

When we view the log, we can see that the macro returns Does Not Exist since a dataset called data2 has never been created.

Note: You can find the complete documentation for the EXIST function in SAS here.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Delete Datasets in SAS
How to Rename Variables in SAS
How to Create New Variables in SAS

You may also like