%let dsid=%sysfunc(open(&dsn));
%if &dsid ne 0 %then %do; %let cnt=%sysfunc(attrn(&dsid,nvars));
%do i = 1 %to &cnt;
%let x=&x %sysfunc(varname(&dsid,&i));
%end;
%end;
%else %put &dsn cannot be open.;
%let rc=%sysfunc(close(&dsid));
%mend lst;
%lst(one)
%put macro variable x = &x;
Program Description
Create a data set.
data one;
input x y;
datalines;
1 2
;
Begin the macro definition that contains one parameter.
%macro lst(dsn);
Create the macro variable named &DSID that uses the OPEN function to open the data
set that is passed to the macro. Use the %IF condition to make sure the data set opened
successfully. If the value is yes, then create the macro variable named &CNT that uses
the ATTRN function with the NVARS argument to return the number of variables that
are contained within the SAS data set.
%local dsid cnt rc;
%global x;
%let x=;
%let dsid=%sysfunc(open(&dsn));
%if &dsid ne 0 %then %do; %let cnt=%sysfunc(attrn(&dsid,nvars));
Use the %DO statement to loop through the number of variables within the SAS data set.
%do i = 1 %to &cnt;
Create the macro variable named &X that uses the VARNAME function to return the
name of a SAS data set variable. The first argument to this function specifies the SAS
data set identifier from the OPEN function. The second argument is the number of the
variable’s position. Each time through the %DO loop the value of &X is appended to
itself.
%let x=&x %sysfunc(varname(&dsid,&i));
End the %DO blocks.
%end;
%end;
Example 5: Place All SAS Data Set Variables into a Macro Variable 455