How to format only those records for which ORA-01843 is not thrown?

老子叫甜甜 提交于 2019-12-14 04:22:22

问题


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

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