If the file is empty, the PROC PRINT can read it, but nothing is printed, not even the headers of the report. This article shows a workaround to Print Empty SAS dataset information to the output window.
Method 1: Print empty SAS dataset using the data access function.
To print empty dataset information to the output window, you can data access functions like ATTRN and NLOBS.
data one;
x=1;
run;
data two;
stop;
run;
%macro print(dsn);
%let dsid=%sysfunc(open(&dsn));
%if &dsid ne 0 %then %do;
%let cnt=%sysfunc(attrn(&dsid,nlobs));
%let rc=%sysfunc(close(&dsid));
%if &cnt ne 0 %then %do;
proc print data=&dsn;
title "This is data from data set &dsn";
run;
%end;
%else %do;
data _null_;
title;
file print;
put _page_;
put "Data set &dsn is empty.";
run;
%end;
%end;
%else %put &dsn cannot be open.;
%mend print;
%print(one)
%print(two)
Below is the result for %print(one)
.
Results for %print(two)
.
The OPEN function opens the data set passed to the macro, and the %IF condition ensures the data set has been successfully opened.
The ATTRN function and the NLOBS argument determine the number of observations in the data set that was opened in the OPEN function, and the value is passed into a macro variable named &CNT.
The %IF statement checks &CNT and PROC PRINT is executed when &CNT is not 0.
The DATA step is executed if the %IF statement is false. Using the FILE PRINT statement, you can direct the output produced by the PUT statements to the same file.
An error message is written to the log if %ELSE cannot open the data set.
Method 2: Conditionally Print empty SAS datasets or Non-Empty datasets using Proc Print
If the dataset is empty, we want to print a message in the output window that there is no data.
In this example, there are two possible scenarios.
The first case is when the table is not empty, and then the dataset will be printed.
The second scenario occurs when a dataset has no data, and a “no data” message must be displayed.
data no_data;
msg = 'No Data';
run;
/*Case 1 - Data set with records*/
data tbl_1;
x=1;
run;
/*Case 2 - Data set without records*/
data tbl_2;
If 0;
run;
data _null_;
dsnid=open('tbl_2');
if dsnid then nobs=attrn(open('tbl_2'), 'nobs' );
if nobs=0 then call execute('proc print data=no_data; run;');
else call execute('proc print data=tbl_2; run;');
run;
Result for Case 1 – dataset tbl_1
Result for Case 2 – dataset tbl2
We use the OPEN function to open the data set and the %IF condition to make sure the data set opened successfully.
The number of observations in the data set that was opened with the OPEN function is determined by the ATTRN function and the NOBS argument. This number is then sent to a macro variable called &CNT.
The IF statement and Call Execute are used to execute the Proc Print code inside the call execute routine.