简体   繁体   中英

I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format

I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format. Please suggest how to approach this?

I did tried but it is failing as it is failing due to invalid month. Is there a way i can first identify what format the date is and then based on case statement i might convert. or something easy way? Please

I trust you've learnt your lesson and you're now going to store these dates in the date data type.

Your two different date formats actually aren't important, Oracle already is a little over accepting when it comes to separating characters. eg

to_date('01/01/1900','dd-mm-yyyy') 

Does not error

I did tried but it is failing as it is failing due to invalid month.

Your error is coming because you've allowed a value that doesn't match either of those formats into your string column.

If you are on version 12.2 at least (which you should be in 2020) then you can use the validate_conversion function to identify rows that don't convert to a date with your format ( https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/VALIDATE_CONVERSION.html#GUID-DC485EEB-CB6D-42EF-97AA-4487884CB2CD )

select string_column
from  my_table
where  validate_conversion(string_column AS DATE,'dd/mm/yyyy') = 0

The other additional helper we got in 12.2 was the on conversion error clause of to_date . So you can do.

alter table my_table add my_date date;
update my_table set my_date = to_date(my_string default null on conversion error,'dd/mm/yyyy');

If you are confident that there is no other format than those two, a simple approach is replace() :

update mytable set mystring = replace(mystring, '/', '-');

This turns all dates to format dd-mm-yyyy .

I would suggest taking a step forward and convert these strings to a date column.

alter table mytable add mydate date;
update mytable set mydate = to_date(replace(mystring, '/', '-'), 'dd-mm-yyyy');

This will fail if invalid date strings are met. I tend to consider that a good thing, since it clearly signals that this a problem with the data. If you want to avoid that, you can use on conversion error , available starting Oracle 12:

to_date(
    replace(mystring, '/', '-') default null on conversion error,
    'dd-mm-yyyy' 
)

Then you can remove the string column, which is no longer needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM