非日期列转换为日期列--函数实现

1.需求

原本日期列,使用的是字符串类型,写入了各种格式的数据,如:

2014年12月12日,

2012/3/8

2015-09-36

2014

18234529999

....

2.具体实现

function get_dateformat(in_string varchar2) return date as
    v_mid_string varchar2(20);
    v_year       varchar2(20); --
    v_month      varchar2(2); --
    v_day        varchar2(2); --
  begin
    if in_string is null or in_string = '1' or length(in_string) < 8 then
      return null;
    end if;
  
    --劈开字符串
    with day_format as
     (select regexp_substr(name_, '[0-9]+', 1, rownum) name_, rownum rn
        from (select in_string name_ from dual)
      connect by regexp_substr(name_, '[0-9]+', 1, rownum) is not null)
    select (select name_ from day_format where rn = 1),
           (select name_ from day_format where rn = 2),
           (select name_ from day_format where rn = 3)
      into v_year, v_month, v_day
      from dual;
  
    --判断年,月,日是否正常
    v_year  := substr(v_year, 1, 4);
    v_month := lpad(v_month, 2, '0');
    if v_month > '12' then
      v_month := '12';
    end if;
    v_day := lpad(v_day, 2, '0');
    if v_day > '31' then
      v_day := '28';
    end if;
  
    v_mid_string := v_year || v_month || v_day;
    if length(v_mid_string)<8 then return null; end if;
  
    return to_date(v_mid_string,'yyyymmdd');
  exception
    when others then
      --dbms_output.put_line(sqlcode || sqlerrm);
      return null;
  end get_dateformat;
原文地址:https://www.cnblogs.com/Alex-Zeng/p/6094212.html