More than one way, as usual.
https://www.listendata.com/2017/04/number-of-observations-in-sas-data.html
Probably the simplest to understand - note the table names are upper case.
proc sql noprint;
select nobs into :totobs separated by ' ' from dictionary.tables
where libname='SASHELP' and memname='CARS';
quit;
%put total records = &totobs.;
Use the &totobs value in the data step as needed.
data want;
x=&totobs;
run;
More than one way, as usual.
https://www.listendata.com/2017/04/number-of-observations-in-sas-data.html
Probably the simplest to understand - note the table names are upper case.
proc sql noprint;
select nobs into :totobs separated by ' ' from dictionary.tables
where libname='SASHELP' and memname='CARS';
quit;
%put total records = &totobs.;
Use the &totobs value in the data step as needed.
data want;
x=&totobs;
run;
why you dont need dot here after &totobs
data want;
x=&totobs;
run;
If the macro variable name is not part of a longer string which might be a SAS name, the dot is not needed, but it is considered good practice (especially for beginners!) to always terminate a macro reference with a dot.
Dot-terminated strings will also have distinct coloring in the Enhanced Editor.
See Maxim 48.
Query the DICTIONARY tables:
proc sql noprint;
select nobs into :number
from dictionary.tables
where libname = "WORK" and memname = "A";
quit;
%put number of obs = &number.;
This is a good situation to use the "IF 0 THEN SET .... NOBS=...;" statement, as in
data want;
if 0 then set table_a (drop=_all_) nobs=number_of_drivers;
set sashelp.cars (keep=make model msrp);
perdriver_cost=msrp/number_of_drivers;
run;
Three points:
A nice feature of this approach is that it doesn't require using a separate procedure to get the number of observations, nor the creation of macrovars, or the use of special functions in the data step.
/*
I prefer this code.
*/
%let dsid=%sysfunc(open(sashelp.class));
%let nobs=%sysfunc(attrn(&dsid.,nlobs));
%let dsid=%sysfunc(close(&dsid.));
%put sashelp.class has &nobs records.;
%let dsid=%sysfunc(open(sashelp.class));
%let nobs=%sysfunc(attrn(&dsid.,nlobs));
%let dsid=%sysfunc(close(&dsid.));
%put sashelp.class has &nobs records.;
data num_records;
num_obs = &nobs;
run;
In the solution I posted, the table names need to be capitalized.
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.