I have a table1(DueDate varchar2(20)). It has thousands of date data in different format with some bad data like characters.
eg.
YYYYMMDD,
MM/DD/YYYY,
MM-DD-YYYY,
M/D/YYYY,
'ABCD'
YYYYMMD,
YYYYMDD,
Now I had to get the dates that are past one week overdue. How do I do that?
Thank you for your help.
This answer builds on Justin Cave’s. If you create another column that is a date field you can then do something like the following:
You could then re-run this update after each modification of the date format in the function. You would have to stop when all the dates not converted are invalid dates (such as ‘ABCD’).
Pure SQL solution for Oracle 12.2, where the handy
default null on conversion error
option avoids the need to write functions and handle exceptions:Results:
The first test does not specify any format in order to use the session default (
DD-MON-RRRR
etc).The next test attempts to handle the North American habit of placing the month first. (I'm not sure if
sys_context('USERENV','NLS_TERRITORY') = 'AMERICA'
is a reliable test though, as that tends to be the default setting regardless of actual territory. However it illustrates how you can inject some conditional logic if desired.)to_date
is pretty forgiving about separator characters so I haven't specified different formats forDD-MON-YYYY
vsDD/MON/YYYY
etc.This is one of the reasons that storing date information in a character field is such a bad idea.
The easiest option is to create a function that attempts to convert the string to a date using the formats in whatever priority order you have (i.e. is 010203 Jan 2, 2003 or Feb 3, 2001 or something else) and catches the exceptions. Something like
which works something like
Of course, you'd have to code the full set of valid date formats in your code, I'm just handling the first two in your list.