0

I have a column with the below sample data. The data type of the column is VARCHAR2.

050211
042911
110428
110428
AO0102
JAN 31
FEB 01

When I try to format the column records in a readable format with below code, I am getting

ORA-01843 : Not a valid month 

SELECT to_char(to_date(TRIM(MyColumn), 'YYMMDD'), 'MM/DD/YYYY') FROM MyTable;

I believe ORA-01843 is thrown because of the records AO0102, JAN 31, FEB 01.

How can I ignore those records(and may be just display its original value) which throw ORA-01843 and format only those records which could be formatted in plain SQL select statement?

user2488578
  • 896
  • 4
  • 21
  • 40
  • You may refer my answer here : https://stackoverflow.com/questions/49402344/regexp-like-for-anything-not-like-mm-dd-yyyy/49402733#49402733 – Kaushik Nayak Apr 11 '18 at 11:02

1 Answers1

1

Use a CASE expression which checks the state of the column, and only conditionally tries to parse as a valid date:

SELECT
    MyColumn,
    CASE WHEN REGEXP_LIKE(MyColumn, '^\s*\d\d\d\d\d\d\s*$')
         THEN TO_CHAR(TO_DATE(TRIM(MyColumn), 'YYMMDD'), 'MM/DD/YYYY')
         ELSE MyColumn END AS new_col
FROM MyTable

But as a general comment, you should avoid storing date information in your tables as text. You are now seeing one of the reasons for avoiding this.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360