Wednesday, January 10, 2018

Condition execution on row count

Use this code as a template for scenarios when you want to change how a SAS program runs depending on whether a data set is empty or not empty. For example, when a report is empty, you may want to not send an email with what would be a blank report. In other words, the report sends only when it has information.

On the other hand, you may want to send an email when a data set is empty if that means an automated SAS program had an error that requires manual intervention.

In general, it's good practice in automated SAS programs to check the size of a data sets in case they are empty or otherwise have the wrong number of observations. With one easy tweak, you could check for a specific minimum number of observations that is greater than zero. (This is left as an exercise for the reader.)



/*
This creates a sample data set with one record.
*/
data mydata;
 input x;
datalines;
1
;
 
/*
This creates a sample data set with zero records.
It has the same name as above, so if you want to test the scenario
with a non-empty data set, simply do not run this step.
*/
data mydata;
 input x;
datalines;
;
 
/*
Count the number of observations, and store the count in a
macro variable.
*/
data _null_;
 if 0 then set mydata nobs=record_count;
 call symput('mv_record_count', put(record_count, 20.));
 stop;
run;
 
/* Print count to the log. */
%put &=mv_record_count;
 
/* Define a macro */
%macro conditional_run;
%if &mv_record_count gt 0 %then %do;
 %put NOTE: this runs when the data set is not empty;
%end;
%else %do;
 %put NOTE: this runs when the data set is empty;
%end;
%mend;
 
/* Run macro */
%conditional_run;

I tested this on SAS 9.4 on Windows 7, though it should work on practically all SAS systems.

No comments:

Post a Comment

Get HTML of iframes in Microsoft Playwright

Playwright is a powerful framework for web testing and automation. This article demonstrates how to extract the HTML content of child IFRAME...