/******************************************************************************************\ | Title: Reordering Variables in a data set. | | Goal: To reorder the variables in a SAS Data set into alphabetical order. | \******************************************************************************************/ /* Create a sample data set */ data a; input x a j z$ q $ ; cards; 1 2 3 qwe asd ; run; /* Use PROC CONTENTS to generate an output data set, keeping only the variable names. In */ /* the output data set from PROC CONTENTS, the variable NAME contains the variable names */ /* in alphabetical order. */ proc contents data=a out=newa(keep=name); run; /* Use a DATA _NULL_ to store each variable in a macro variable named &VAR1, &VAR2, etc */ /* and put the total number of variables into a macro variable &TOTAL. */ data _null_; set newa end=last; i+1; call symput('var'||trim(left(put(i,8.))),trim(name)); if last then call symput('total',trim(left(put(i,8.)))); run; /* Use a macro DO Loop to generate the names of the variables for a DATA Step to process */ /* in a RETAIN statement. Placing the variable names on a RETAIN statement prior to the */ /* SET statement ensures the variables are placed in the PDV in that order. */ %macro test; data final; retain %do j=1 %to &total; &&var&j %end;; set a; proc print;run; %mend test; /* Finally, invoke the macro. */ %test