In this example page, I will demonstrate code example of how to determine the number of observations in a SAS data set. Without reading the entire data set. I will demonstrate three different approaches. In all three cases, I will put the number of rows into a macro variable. In the examples to come, I will use the sashelp.class data set. It has 19 observations.
Using the Nobs= Option
First, let us use the SAS data step to determine the number of observations in the sashelp.class. In the data step below, I use the if 0 then set trick to prevent execution. In the Set Statement, I use the Nobs= Option to assign the number of observations to the variable n. This works, because the Nobs= Options is set at compile time. Not Execution. Finally, I use the Call Symput Routine to assign the number of observations to the macro variable nobs.
data _null_; if 0 then set sashelp.class nobs=n; call symputx('nobs',n); stop; run; %put nobs=&nobs;
Using Open, Attrn and Close Functions wrapped in %sysfuncs
Next, we can also use the high level SAS functions Open, Attrn and Close Functions. In this example, I wrap them in %Sysfunc Macro Functions. This way, I do not have to use the data step. So, in the example below, I open the sashelp.class data set. Then I retrieve the number of observations and close it again.
%let dsid=%sysfunc(open(sashelp.class)); %let nobs=%sysfunc(attrn(&dsid,nobs)); %let dsid=%sysfunc(close(&dsid)); %put nobs= &nobs;
Retrieve Information from Metadata
As a final example, we can also get the information about observation number from metadata. In the data step below, I read the sashelp.vtable metadata table. Then, I subset the data on libname and memname to navigate to the sashelp.class data set. Finally, I read the value that is in the nobs column.
data _null_; set sashelp.vtable; where libname='SASHELP' & MEMNAME='CLASS'; call symputx('nobs',nobs); run; %put nobs= &nobs ;
On this page, I demonstrate three different ways to get the number of observations in a SAS Data Step. Without reading the entire thing. There is not a right and wrong approach to this problem and the list on this page is not exhausting. There are many other ways to do this. However, all three approaches are pretty efficient. Of course the third approach depends on the metadata size.
You can download the entire code from this example page here.