问题
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?
回答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.
来源:https://stackoverflow.com/questions/49773170/how-to-format-only-those-records-for-which-ora-01843-is-not-thrown