SAS 9.4. I want to merge datasets DATA1 and DATA2. there is complete variable name…
- User
SAS 9.4.
I want to merge datasets DATA1 and DATA2.
there is complete variable name overlap between the two datasets.
therefor we need a merge or join that will automatically handle name conflicts, perhaps by automatically adding a prefix or a suffix.
Assistant
In SAS 9.4, when merging datasets with identical variable names, you need to manually resolve name conflicts — SAS does not automatically rename variables with prefixes or suffixes during a merge.
However, you can automate the renaming using the
dictionary.columnstable and dynamic code generation. Here's a macro that will:- Rename all variables in
DATA2by adding a suffix (e.g.,_2) - Then merge
DATA1and the renamedDATA2by a key variable (e.g.,ID)
✅ Example Macro: Auto-Rename and Merge
%macro merge_with_suffix(data1=, data2=, key=, suffix=_2, out=merged); /* Step 1: Get list of variables from DATA2 */ proc sql noprint; select name into :vars2 separated by ' ' from dictionary.columns where libname = upcase("WORK") and memname = upcase("&data2"); quit; /* Step 2: Build rename list */ %let rename_list=; %do i=1 %to %sysfunc(countw(&vars2)); %let var = %scan(&vars2, &i); %let rename_list = &rename_list &var=&var.&suffix; %end; /* Step 3: Rename DATA2 variables and merge */ data &out; merge &data1 &data2(rename=(&rename_list)); by &key; run; %mend;- Rename all variables in
- User
made changes to the macro. final version is:
%macro merge_with_suffix(data1=, data2=, key=, suffix=_2, out=merged); proc sql noprint; select name into :vars2 separated by ' ' from dictionary.columns where libname = upcase("WORK") and memname = upcase("&data2") and upcase(name) ne upcase("&key"); quit; %let rename_list=; %do i=1 %to %sysfunc(countw(&vars2)); %let var = %scan(&vars2, &i); %let rename_list = &rename_list &var=&var.&suffix; %end; data &out; merge &data1(in=in1) &data2(rename=(&rename_list) in=in2); by &key; if in1 and in2; run; %mend;
%merge_with_suffix(data1=DATA1, data2=DATA2, key=ID, suffix=_2, out=MERGED);
Assistant
Your macro is clean and will work as intended under the assumptions you’ve made:
- both input data sets are in the WORK library
- the BY variable is named exactly the same in both data sets
- you only want to keep the records that match in both data sets (
if in1 and in2) - you want every non-key variable from DATA2 to be suffixed with “_2”
Nothing in the macro violates SAS 9.4 syntax or capabilities, so you can run it as-is.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.