Adding leading zero if length is not equal to 10 digit using sql

moe picture moe · Nov 1, 2013 · Viewed 23.9k times · Source

I am trying to join 2 tables but my problem is that one of the table has 10 digit number and the other one may have 10 or less digit number. For this reason, i am loosing some data so i would like to do is check the length first if the length is less than 10 digit then i want to add leading zeros so i can make it 10 digit number. I want to do this when i am joining this so i am not sure if this is possible. Here is an example if i i have 251458 in the TABLE_WITHOUT_LEADING_ZERO then i want to change it like this: 0000251458. Here is what i have so far:

select ACCT_NUM, H.CODE
 FROM TABLE_WITH_LEEDING_ZERO D,  TABLE_WITHOUT_LEADING_ZERO H
 WHERE substring(D.ACCT_NUM from position('.' in D.ACCT_NUM) + 2) = cast (H.CODE as varchar (10))

thanks

Answer

bma picture bma · Nov 1, 2013

Another alternative:

SELECT TO_CHAR(12345,'fm0000000000');
  to_char   
------------
 0000012345