简体   繁体   中英

How to Insert '/' after 2nd and 4th char in varchar column of an Oracle table

I am new to Oracle and working in Oracle 10g. I have a table WW_WAGEMAST and it has a column of type varchar2(11) for saving PF_Join_date . It has date in both format ddmmyyyy and dd/mm/yyyy . I want to convert all date in single format dd/mm/yyy. How can I do that ?

For example - current situation:

PF_JOIN_DATE
------------
01/04/2018 
02042018 
03042018 
04/04/2018 
05042018

I need to change all to a single format like this:

PF_JOIN_DATE
---------------
01/04/2018 
02/04/2018 
03/04/2018 
04/04/2018 
05/04/2018

How can I do that? Please help me. Thanks in advance.

You can write:

update WW_WAGEMAST
set PF_JOIN_DATE = substr(PF_JOIN_DATE, 1, 2) || '/' ||
                   substr(PF_JOIN_DATE, 3, 2) || '/' ||
                   substr(PF_JOIN_DATE, 5, 4)
where PF_JOIN_DATE not like '%/%'

this will work:

CREATE TABLE d061_Table1
    ("PF_JOIN_DATE" varchar2(10))
;

INSERT ALL 
    INTO d061_Table1 ("PF_JOIN_DATE")
         VALUES ('01/04/2018')
    INTO d061_Table1 ("PF_JOIN_DATE")
         VALUES ('02042018')
    INTO d061_Table1 ("PF_JOIN_DATE")
         VALUES ('03042018')
    INTO d061_Table1 ("PF_JOIN_DATE")
         VALUES ('04/04/2018')
    INTO d061_Table1 ("PF_JOIN_DATE")
         VALUES ('05042018')
SELECT * FROM dual
;

select * from d061_Table1;
update d061_Table1 set PF_JOIN_DATE=
(substr(PF_JOIN_DATE, 1, 2) || '/' ||
          substr(PF_JOIN_DATE, 3, 2) || '/' ||
          substr(PF_JOIN_DATE, 5, 4))
where not regexp_like(PF_JOIN_DATE, '^[0-9]{2,}/{1}[0-9]{2,}/{1}[0-9]{4,}$');

select * from d061_Table1;

output:
01/04/2018
02/04/2018
03/04/2018
04/04/2018
05/04/2018

With regexp.

update plv_test_table t
set t.pf_join_date = regexp_replace(t.pf_join_date, '^(\d{2})(\d{2})(\d{4})$','\1/\2/\3')

Optionally - depending on size of your table it can be faster to update all or only part of rows. Without where clause this query still correct.

where t.pf_join_date not like '%/%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM