0

I have this table where VARCHAR2(128 CHAR) field could be of the format 2018-01-01 00:00:00 or 01/01/2018 00:00:00 or 01-JAN-2018 00:00:00

How can I pull records that has the VARCHAR2(128 CHAR) field in 2016-01-01 00:00:00 or 01-JAN-2018 00:00:00 format alone?

Chrᴉz remembers Monica
  • 1,829
  • 1
  • 10
  • 24
Mike
  • 721
  • 1
  • 17
  • 44

2 Answers2

1

Not good storing a date in a varchar. But as it is like this, I would propose converting the string to a date and then back to string again. Like so:

declare
  d date;
begin
  begin
    d:=to_date('01.01.2011 23:49:00','dd/mm/yyyy hh24:mi:ss');
  exception
    when others then
      begin
        d:=to_date('01.01.2011 23:49:00','dd.mm.yyyy hh24:mi:ss');
      exception
        when others then
          begin
            d:=to_date('01.01.2011 23:49:00','dd-mm-yyyy hh24:mi:ss');
          exception
            when others then
              -- any more date format strings?
              null;
          end;
      end;
  end;
  dbms_output.put_line(to_char(d,'dd-mm-yyyy hh24:mi:ss'));
end;
/
sers
  • 3,139
  • 3
  • 20
  • 28
1

Create a function that converts a date string to date:

create or replace function date_from_string(str varchar2, fmt varchar2) return date is
    v date;
begin
    return to_date(str,fmt);
exception when others
    then return null;
end;

And query the table, for example:

with t as (
select case when regexp_like(field, '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$') 
              then 'YYYY-MM-DD HH24:MI:SS'
            when regexp_like(field, '^\d\d-[a-zA-Z]{3}-\d{4} \d\d:\d\d:\d\d$') 
              then 'DD-MON-YYYY HH24:MI:SS'
             end fmt, t.*
from "TABLE" t
)
select t.*, date_from_string(t.field, t.fmt) "DATE" from t
where date_from_string(t.field, t.fmt) is not null;

This way you can easily check that the date in a given record is correct.

wolfrevokcats
  • 2,100
  • 1
  • 12
  • 12