Table1 Table2
NUM NUM
12345678 012345678
9876543 009876543
Are the columns numeric or character?
What do you mean by 'MERGE'? What is your hoped for result?
Do you just need to add leading zeros? This DATA step creates a second variable with leading zeros.
data have(drop=len);
length x1 x2 $9;
input x1 $;
x2='000000000';
len=length(x1);
substr(x2,9-len+1) = x1;
datalines;
1
1234
run;
Let's break down the code a bit:
First I am going to initialize X2 to all zeros.
x2='000000000';
We will need to know how many characters are in X1 (there are other ways to count characters, but this is easy).
len=length(x1);
The SUBSTR function can be used on either the left or right of the equal sign. When it is used on the right it extracts characters from the string. When it is used on the left it inserts characters. Here we want to insert the characters contained in X1 into X2. This replaces corresponding preloaded zeros. The second argument (9-len+1) tells SUBSTR where to start the insertion. I could have written this argument as 10-len.
substr(x2,9-len+1) = x1;
Hopefully X2 can now be used to match the variables in the other data set that already have the leading zeros. I am assuming that the numbers themselves are some kind of coded value. It is, therefore, probably safer to leave them as character strings. Merging using numeric values can have some unintended consequences (there are rounding and storage issues).
To left fill '0's, aside from ArtC's igneous left-substr() approach (BTW, Art and all, are there any other functions can be applied like this? I can't recall any), here is another more conventional approach (borrowing Art's data):
data have;
length x1 x2 $9;
input x1 $;
x2=put(input(x1,best.),z9.);
datalines;
1
1234
run;
Haikuo
So why convert back to character after converting to numeric? Why not just stop at
x2=input(x1,best.);
and do the merge using numeric values?
That's the basis for the proc sql statement discussed above.
Well, according to OP's post (3rd one from top), both x1 and x2 are char.
Haikuo
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.