check for valid date which is declared in varchar2

前端 未结 1 1605
难免孤独
难免孤独 2021-01-16 15:54

My table looks like below which is declared in VARCHAR2:

YMD  
20101010  
20101112  
20100231  
20150101  
20160101  

I have to check for

相关标签:
1条回答
  • 2021-01-16 16:11

    I will rather fix the design issue as a permanent fix rather than wasting time on the workaround.

    Firstly, NEVER store DATE as VARCHAR2. All this overhead is due to the fact that your design is flawed.

    '20100231'

    How on earth could that be a valid date? Which calendar has a 31 days in FEBRUARY?

    Follow these steps:

    1. Add a new column with DATE DATA TYPE.
    2. Update the new column with date values from the old column using TO_DATE.
    3. Do the required DATE arithmetic on the new DATE column, or handle this in the UPDATE statement in step 2 itself.
    4. Drop the old column.
    5. Rename the new column to the old column.

    UPDATE Adding a demo

    Setup

    SQL> CREATE TABLE t
      2      (ymd varchar2(8));
    
    Table created.
    
    SQL>
    SQL> INSERT ALL
      2      INTO t (ymd)
      3           VALUES ('20101112')
      4      --INTO t (ymd)
      5      --     VALUES ('20100231')
      6      INTO t (ymd)
      7           VALUES ('20150101')
      8      INTO t (ymd)
      9           VALUES ('20160101')
     10  SELECT * FROM dual;
    
    3 rows created.
    
    SQL>
    SQL> COMMIT;
    
    Commit complete.
    
    SQL>
    

    Add new column:

    SQL> ALTER TABLE t ADD (dt DATE);
    
    Table altered.
    
    SQL>
    

    DO the required update

    SQL> UPDATE t
      2  SET dt =
      3    CASE
      4      WHEN to_date(ymd, 'YYYYMMDD') > SYSDATE
      5      THEN NULL
      6      ELSE to_date(ymd, 'YYYYMMDD')
      7    END;
    
    3 rows updated.
    
    SQL>
    SQL> COMMIT;
    
    Commit complete.
    
    SQL>
    

    Let's check:

    SQL> SELECT * FROM t;
    
    YMD      DT
    -------- ---------
    20101112 12-NOV-10
    20150101 01-JAN-15
    20160101
    
    SQL>
    

    Drop the old column:

    SQL> ALTER TABLE t DROP COLUMN ymd;
    
    Table altered.
    
    SQL>
    

    Rename the new column to old column name

    SQL> ALTER TABLE t RENAME COLUMN dt TO ymd;
    
    Table altered.
    
    SQL>
    

    You have just fixed the issue

    SQL> SELECT * FROM t;
    
    YMD
    ---------
    12-NOV-10
    01-JAN-15
    
    
    SQL>
    
    0 讨论(0)
提交回复
热议问题