/* In programming statistical routines in SAS, one of the things you need as a programmer is to grab the names of the variables in the dataset. SAS has some special functions to do this that require using a do loop that looks at each column from left to write. Once you loop through the names, you can write them out to a file. In this example, we simply write the names of the variables to a text file: c:\names.txt. Although you could get the variable names other ways (proc contents, etc.), this serves as a good illustration of looping and the special sysfunctions of SAS. */ *First we read in a test data set for you; data mydata; input Y VAR1 VAR2 VAR3; cards; 1 10 33 4 0 20 21 3 1 30 59 2 1 20 76 1 0 30 24 3 0 20 22 2 1 10 28 2 1 10 49 2 0 30 76 2 1 20 59 2 ; %macro getnames(dsn,myfile); *reads data into another dataset for illustration purposes; *dsn is the name of the dataset you pass in the macro; *The 2nd thing you pass is what you want to call the output file; data testdata; set &dsn; file &myfile; run; *The following line useful whenever you run a macro because it prints out all the steps.; OPTIONS NOTES SOURCE SOURCE2 MPRINT MLOGIC MERROR SYMBOLGEN; %let dsid=%sysfunc(open(&dsn)); %let cnt=(%sysfunc(attrn(&dsid,nvars))); %do i = 1 %to &cnt; %let myname=%sysfunc(varname(&dsid,&i)); data _null_; /*_null_ means you only read the file, you don't save it */ set &dsn end=last; file &myfile mod; if last then put "&myname"; run; %end; %let rc=%sysfunc(close(&dsid)); %mend getnames; %getnames(mydata,'c:\names.txt');