Example 8: Dynamically Determine the Number of
Observations and Variables in a SAS Data Set
Details
This macro uses the functions OPEN and ATTRN to retrieve the total number of
observations and variables contained within a SAS data set.
Program
data test;
input a b c $ d $;
datalines;
1 2 A B
3 4 C D
;
%macro obsnvars(ds);
%global dset nvars nobs;
%let dset=&ds;
%let dsid = %sysfunc(open(&dset));
%if &dsid %then %do;
%let nobs =%sysfunc(attrn(&dsid,nlobs));
%let nvars=%sysfunc(attrn(&dsid,nvars));
%let rc = %sysfunc(close(&dsid));
%end;
%else %put open for data set &dset failed - %sysfunc(sysmsg());
%mend obsnvars;
%obsnvars(test)
%put &dset has &nvars variable(s) and &nobs observation(s).;
Program Description
Create a data set named Test.
data test;
input a b c $ d $;
datalines;
1 2 A B
3 4 C D
;
Begin the macro definition with one parameter.
%macro obsnvars(ds);
460 Appendix 5 SAS Macro Examples
Create a global macro variable &DSET from the macro parameter &DS by using
%GLOBAL and %LET statements.
%global dset nvars nobs;
%let dset=&ds;
Use the OPEN function to open the data set that is passed to the macro.
%let dsid = %sysfunc(open(&dset));
Use the %IF statement to make sure the data set was open. If it is open, then run three
%LET statements.
The first %LET statement creates a macro variable named &NOBS. The ATTRN
function is used with the NLOBS argument to retrieve the logical number of
observations in the data set.
The second %LET statement creates a macro variable named &NVARS. The
ATTRN function is used along with the NVARS argument to retrieve the number of
variables in the data set.
The third %LET statement uses the CLOSE function to close the data set that is
passed to the macro.
&DSID is the identifier that is returned from the OPEN function.
%if &dsid %then %do;
%let nobs =%sysfunc(attrn(&dsid,nlobs));
%let nvars=%sysfunc(attrn(&dsid,nvars));
%let rc = %sysfunc(close(&dsid));
%end;
If the %IF condition is false, meaning that the data set is not open, then use the %PUT
statement to write a statement to the log.
%else %put open for data set &dset failed - %sysfunc(sysmsg());
Close the macro definition.
%mend obsnvars;
Invoke the macro by passing in the data set name as a parameter.
%obsnvars(test)
Use the %PUT statement to write the information returned from the macro to the log.
%put &dset has &nvars variable(s) and &nobs observation(s).;
Example 8: Dynamically Determine the Number of Observations and Variables in a SAS
Data Set 461

Get SAS 9.4 Macro Language, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.