Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mf_getvarlist.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Returns dataset variable list direct from header
4  @details WAY faster than dictionary tables or sas views, and can
5  also be called in macro logic (is pure macro). Can be used in open code,
6  eg as follows:
7 
8  %put List of Variables=%mf_getvarlist(sashelp.class);
9 
10  returns:
11  > List of Variables=Name Sex Age Height Weight
12 
13  %put %mf_getvarlist(sashelp.class,dlm=%str(,),quote=double);
14 
15  returns:
16  > "Name","Sex","Age","Height","Weight"
17 
18  @param libds Two part dataset (or view) reference.
19  @param dlm= provide a delimiter (eg comma or space) to separate the vars
20  @param quote= use either DOUBLE or SINGLE to quote the results
21 
22  @version 9.2
23  @author Allan Bowe
24 
25 **/
26 
27 %macro mf_getvarlist(libds
28  ,dlm=%str( )
29  ,quote=no
30 )/*/STORE SOURCE*/;
31  /* declare local vars */
32  %local outvar dsid nvars x rc dlm q var;
33 
34  /* credit Rowland Hale - byte34 is double quote, 39 is single quote */
35  %if %upcase(&quote)=DOUBLE %then %let q=%qsysfunc(byte(34));
36  %else %if %upcase(&quote)=SINGLE %then %let q=%qsysfunc(byte(39));
37  /* open dataset in macro */
38  %let dsid=%sysfunc(open(&libds));
39 
40 
41  %if &dsid %then %do;
42  %let nvars=%sysfunc(attrn(&dsid,NVARS));
43  %if &nvars>0 %then %do;
44  /* add first dataset variable to global macro variable */
45  %let outvar=&q.%sysfunc(varname(&dsid,1))&q.;
46  /* add remaining variables with supplied delimeter */
47  %do x=1 %to &nvars;
48  %let var=&q.%sysfunc(varname(&dsid,&x))&q.;
49  %if &var=&q&q %then %do;
50  %put &sysmacroname: Empty column found in &libds!;
51  %let var=&q. &q.;
52  %end;
53  %if &x=1 %then %let outvar=&var;
54  %else %let outvar=&outvar.&dlm.&var.;
55  %end;
56  %end;
57  %let rc=%sysfunc(close(&dsid));
58  %end;
59  %else %do;
60  %put unable to open &libds (rc=&dsid);
61  %let rc=%sysfunc(close(&dsid));
62  %end;
63  &outvar
64 %mend;