Link to home
Create AccountLog in
Avatar of Metalteck
MetalteckFlag for United States of America

asked on

Not a valid month error in TO_Char to Date line

In my oracle query, I'm getting a not a valid month while using the following line of code:

TO_CHAR(TO_DATE(TRIM(D.MOSTRECENTHIRE),'yyyymmdd'),'yyyy-mm-dd') AS HIREDATE, 

Open in new window

I've tried using:

TO_CHAR(TO_DATE(NULLIF(D.MOSTRECENTHIRE, '00000000'), 'yyyymmdd'), 'yyyy-mm-dd')

Open in new window

But that didn't work either. Suggestions on how I can resolve this?

Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Using '00000000' as a "default" date will generate that error whenever MOSTRECENTHIRE is NULL.


You'll want to check the value with a CASE statement and return your default value when NULL, otherwise make the conversion.



ASKER CERTIFIED SOLUTION
Avatar of Sean Stuber
Sean Stuber

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Sean Stuber
Sean Stuber

Alternately, you could subtitute a dummy value instead of NULL and then look for those values.

to_char(to_date(TRIM(D.MOSTRECENTHIRE) default '00010101' on conversion error,'yyyymmdd'),'yyyy-mm-dd')

Using '00000000' as a "default" date will generate that error whenever MOSTRECENTHIRE is NULL.


The NULLIF function doesn't substitute the '00000000' string when the column is null,
instead, it returns NULL when the column value = '00000000'

you could get fancy by checking validation and then returning either a formatted date string or an error message depending on the validation results.

CASE
           WHEN validate_conversion(TRIM(d.mostrecenthire) AS DATE, 'yyyymmdd') =
                1
           THEN
               TO_CHAR(TO_DATE(TRIM(d.mostrecenthire), 'yyyymmdd'),
                       'yyyy-mm-dd')
           ELSE
               'Error converting value: ' || d.mostrecenthire
       END most_recent_hire