Allan Cumming
Allan Cumming

Reputation: 91

What is the simplest way to either display the data, if there are observations, or create an empty record stating that the dataset was empty?

I have looked around quite a bit for something of this nature, and the majority of sources all give examples of counting the amount of observations etc.

But what I am actually after is a simple piece of code that will check to see if there are any observations in the dataset, if that condition is met then the program needs to continue as normal, but if the condition is not met then I would like a new record to be created with a variable stating that the dataset is empty.

I have seen macros and SQL code that can accomplish this, but what I would like to know is is it possible to do the same in SAS code? I know the code I have below does not work, but any insight would be appreciated.

Data TEST;
    length VAR1 $200.;
    set sashelp.class nobs=n;        
    call symputx('nrows',n);
    obs= &nrows;
    if obs = . then VAR1= "Dataset is empty"; output;    
Run;

Upvotes: 0

Views: 724

Answers (2)

DomPazz
DomPazz

Reputation: 12465

Easiest way I can think of is to use the nobs statement to check the number of records. The trick is you don't want to actually read from an empty data set. That will terminate the DATA Step and the nobs value will not be set. So you use an always false if statement to check the number of observations.

data test1;
format x best. msg $32.;
stop;
run;

data test1;
if _n_ = 0 then
    set test1 nobs=nobs;

if ^nobs then do;
    msg = "NO RECORDS";
    output;
    stop;
end;
set test1;
/*Normal code here*/

output;
run;

So this populates the nobs value with 0. The if clause sees the 0 and allows you to set the message and output that value. Use the stop to then terminate the DATA Step. Outside of that check, do your normal data step code. You need the ending output statement because of the first. Once the compiler sees an output it will not do it automatically for you.

Here it works for a data set with values.

data test2;
format x best. msg $32.;
do x=1 to 5;
msg="Yup";
output;
end;
run;

data test2;
if _n_ = 0 then
    set test2 nobs=nobs;

if ^nobs then do;
    msg = "NO RECORDS";
    output;
    stop;
end;
set test2;
y=x+1;
output;
run;

Upvotes: 0

Jeff
Jeff

Reputation: 1807

You could do it by always appending a 1-row data set with the empty dataset message, and then delete the message if it doesn't apply.

data empty_marker;
    length VAR1 $200;
    VAR1='Dataset is empty';
run;

Data TEST;
    length VAR1 $200.;
    set
        sashelp.class nobs=n
        empty_marker (in=marker)
        ;
    if (marker) and _n_ > 1 then delete;
Run;

Upvotes: 1

Related Questions