Sometimes, we need to change the names of variables in a dataset. This is particularly common in Mendelian randomization studies when merging two datasets with many overlapping variable names. To prevent the overwriting of variables with the same names, we must rename one of them. The following SAS macro is highly efficient for performing this data manipulation.

We added “_hip” to all varialbe names of dataset ONE.

Data one;
 U_2=1;
 V_3=2;
 X_2=3;
 Y_2=4;
 Z_3=5;
Run;

options macrogen mprint mlogic;
%macro rename(lib,dsn);
options pageno=1 nodate;
proc contents data=&lib..&dsn;
title "Before Renaming All Variables";
run;
proc sql noprint;
 select nvar into :num_vars
 from dictionary.tables
 where libname="&LIB" and
 memname="&DSN";
 select distinct(name) into :var1-
:var%TRIM(%LEFT(&num_vars))
 from dictionary.columns
 where libname="&LIB" and
 memname="&DSN";
quit;
run;
proc datasets library=&LIB;
 modify &DSN;
 rename
 %do i=1 %to &num_vars;
 &&var&i=&&var&i.._hip  /**note no semi colon here, very important**/
%end;
;
quit;
run;
options pageno=1 nodate;
proc contents data=&lib..&dsn;
title "After Renaming All Variables";
run;
%mend rename;
%rename(WORK,ONE);/***Note the library and database name should be all in CAPITAL LETTERS)****/

/**results
Alphabetic List of Variables and Attributes 
# Variable Type Len 
1 U_2_hip Num 8 
2 V_3_hip Num 8 
3 X_2_hip Num 8 
4 Y_2_hip Num 8 
5 Z_3_hip Num 8 
****/