日期转换异常处理函数

5880阅读 0评论2013-06-19 十字螺丝钉
分类:Oracle

工作中常会使用to_date函数,将文本转换成日期格式
select to_date('2012-01-03 00:00:00','yyyy-mm-dd hh24:mi:ss') from dual;
 
如果格式有误,to_date()函数就会报错
select to_date('00000101','yyyymmdd') from dual;
ORA-01841: (完整) 年份值必须介于 -4713 和 +9999 之间, 且不为 0
01841. 00000 -  "(full) year must be between -4713 and +9999, and not be 0"
*Cause:    Illegal year entered
*Action:   Input year in the specified range
 
下面的场景遇到这个错误解决起来很麻烦
insert into a
select to_date(log_time,'yyyy-mm-dd hh24:mi:ss')
from b;
如果b表中log_time列有错误数据,就会返回上面的错误。
 
使用函数处理日期转换异常是个不错的选择。
通过日期转换函数可以将正确格式的转换成日期,不正确的做异常处理,输出空。
 
--函数:异常处理日期转换错误
create or replace function  date_fun(p_str in NVARCHAR2) return date is
v_ret date;
 begin  
     begin
      v_ret:=to_date(p_str,'yyyy-mm-dd hh24:mi:ss');
      exception
       when OTHERS then  null;
     end;  
     return v_ret;             
  end;
  /
上一篇:恢复truncate表的数据
下一篇:kvm虚拟机无法启动