How can I format a number as xxx-xx-xxxx?

做~自己de王妃 提交于 2019-12-04 05:08:28

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!