I am querying social security number data from a stored procedure and I would like to format it as a social security number in my stored procedure.
How can I format xxxxxxxxx like xxx-xx-xxxx in Oracle?
I am querying social security number data from a stored procedure and I would like to format it as a social security number in my stored procedure.
How can I format xxxxxxxxx like xxx-xx-xxxx in Oracle?
SSN formatting with TO_CHAR
SELECT TO_CHAR(012345678, '000g00g0000','nls_numeric_characters=.-') ssn from dual;
SSN
-----------
012-34-5678
update: thanks to Gary for pointing out that the '0' format character should be used rather than the '9' to preserve leading zeroes.
you could also use the concat operator ||
, which might be more readable.
SUBSTR(data, 1, 3) ||'-'||SUBSTR(data, 4, 2)||'-'||SUBSTR(data, 6, 4)
And if you'd like to check if the number consists of 9 digits before applying the format, then regular expressions can be of help:
SQL> create table t (nr)
2 as
3 select 123456789 from dual union all
4 select 987654321 from dual union all
5 select null from dual union all
6 select 1234567 from dual union all
7 select 12345678901234 from dual
8 /
Tabel is aangemaakt.
SQL> select nr
2 , regexp_replace(nr,'(^[[:digit:]]{3})([[:digit:]]{2})([[:digit:]]{4}$)','\1-\2-\3') formatted_nr
3 from t
4 /
NR FORMATTED_NR
-------------------------------------- --------------------
123456789 123-45-6789
987654321 987-65-4321
1234567 1234567
12345678901234 12345678901234
5 rijen zijn geselecteerd.
Regards, Rob.
CONCAT(CONCAT(CONCAT(CONCAT(SUBSTR(sspdata, 1, 3), '-'), SUBSTR(sspdata, 4, 2)), '-',) SUBSTR(sspdata, 6, 4))