一个简单的思路:
取出这部分字符串后看能不能做to_date转换,如果成功就合法

解决方案 »

  1.   

    我想把身份证中7-14位是非法的日期的人员查询出来,用to_date会出错。
      

  2.   

    SQL*Plus: Release 8.0.5.0.0 - Production on 星期二 12月 21 14:20:58 2004(c) Copyright 1998 Oracle Corporation.  All rights reserved.
    连接到:
    Oracle8 Release 8.0.5.0.0 - Production
    PL/SQL Release 8.0.5.0.0 - ProductionSQL> create or replace function isdate(mydate in varchar2)
      2  return char is
      3  tmp date;
      4  begin
      5  tmp:=to_date(mydate,'yyyymmdd');
      6  return '1';
      7  exception
      8      when others then
      9          return '0';
     10  end isdate;
     11  /函数已创建。SQL> select isdate(substr('320102199901012015',7,8)) from dual;ISDATE(SUBSTR('320102199901012015',7,8))
    ----------------------------------------------------------------------------------------------------
    1SQL> select isdate(substr('320102199901322015',7,8)) from dual;ISDATE(SUBSTR('320102199901322015',7,8))
    ----------------------------------------------------------------------------------------------------
    0SQL>
      

  3.   

    1。建立函数:
    CREATE OR REPLACE FUNCTION is_date
    (
      p_period_start varchar2 default null
    )
    RETURN NUMBER 
    IS
    tmpVar NUMBER;
    tmpDate date;
    /******************************************************************************
       NAME:       is_date
       PURPOSE:       REVISIONS:
       Ver        Date        Author           Description
       ---------  ----------  ---------------  ------------------------------------
       1.0        2004-12-21          1. Created this function.   NOTES:   Automatically available Auto Replace Keywords:
          Object Name:     is_date
          Sysdate:         2004-12-21
          Date and Time:   2004-12-21, 14:25:35, and 2004-12-21 14:25:35
          Username:         (set in TOAD Options, Procedure Editor)
          Table Name:       (set in the "New PL/SQL Object" dialog)******************************************************************************/
    BEGIN
       /* confirm if null*/
       if (p_period_start is not null) then
       begin 
       tmpDate := to_date(p_period_start,'yyyy-mm-dd hh24:mi:ss');
       tmpVar := 1;
       end;
       else
           tmpVar := 0;
       end if;
           
       RETURN tmpVar;
       
       EXCEPTION
         WHEN NO_DATA_FOUND THEN
           NULL;
         WHEN OTHERS THEN
     begin
           -- Consider logging the error and then re-raise
           tmpVar := 0;
           RETURN tmpVar;  
       RAISE;
     end;END is_date;
    /
    2、查询日期不对的sql:
    select ×
    from table
    where is_date(substr(key_date_str,7,8)) = 0