Oracle Date column cleaning

前端 未结 3 1695
遥遥无期
遥遥无期 2020-12-12 05:07

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/YYY         


        
3条回答
  •  旧巷少年郎
    2020-12-12 05:44

    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

    CREATE OR REPLACE FUNCTION my_to_date( p_str IN VARCHAR2 )
      RETURN DATE
    IS
      l_date DATE;
    BEGIN
      l_date := to_date( p_str, 'YYYYMMDD' );
      RETURN l_date;
    EXCEPTION
      WHEN others THEN
        BEGIN
          l_date := to_date( p_str, 'MM/DD/YYYY' );
          RETURN l_date;
        EXCEPTION 
          WHEN others
          THEN
            RETURN null;
        END;
    END;
    

    which works something like

    SQL> CREATE OR REPLACE FUNCTION my_to_date( p_str IN VARCHAR2 )
      2    RETURN DATE
      3  IS
      4    l_date DATE;
      5  BEGIN
      6    l_date := to_date( p_str, 'YYYYMMDD' );
      7    RETURN l_date;
      8  EXCEPTION
      9    WHEN others THEN
     10      BEGIN
     11        l_date := to_date( p_str, 'MM/DD/YYYY' );
     12        RETURN l_date;
     13      EXCEPTION
     14        WHEN others
     15        THEN
     16          RETURN null;
     17      END;
     18  END;
     19  /
    
    Function created.
    
    SQL> select my_to_date( '19000101' ) from dual;
    
    MY_TO_DAT
    ---------
    01-JAN-00
    
    SQL> ed
    Wrote file afiedt.buf
    
      1* select my_to_date( '01/02/2005' ) from dual
    SQL> /
    
    MY_TO_DAT
    ---------
    02-JAN-05
    

    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.

提交回复
热议问题