如何修复年份格式异常ORA-01841?

时间:2018-05-31 12:48:59

标签: sql oracle plsql

我有这个功能,当天不合格时,需要一个月的最后一天:

create or replace function updateDate(p_date varchar2) return date as
  l_date date;
  e_bad_day exception;
  pragma exception_init (e_bad_day, -1847);
begin
  begin
    -- try to convert

    l_date := to_date(p_date ,'yyyymmdd')  ;
  exception
    when e_bad_day then
      -- ignore the supplied day value and get last day of month
      l_date := last_day(to_date(substr(p_date, 1, 6), 'yyyymm'));
  end;
  return l_date;
end;

在我遇到这些错误之前一切正常。似乎有些年份不正确,我该如何解决这个问题?

  

java.sql.SQLDataException:ORA-01841:L'année(complète)doitêtre   包括entre -4713 et +9999etêtredifférentede0

     

ORA-06512:à“CRPCEN1.UPDATEDATE”,ligne 8

我尝试通过添加此声明来修复此问题,但它不起作用,因为我没有使用12g:

to_date(p_date default null on conversion error, 'yyyymmdd')

1 个答案:

答案 0 :(得分:1)

将您的代码更改为:

create or replace function updateDate(p_date varchar2) return date as
  l_date date;
  e_bad_day exception;
  pragma exception_init (e_bad_day, -1847);
begin

  begin
    l_date := to_date(p_date ,'yyyymmdd')  ;
  exception
    when e_bad_day then
         -- ignore the supplied day value and get last day of month
         l_date := last_day(to_date(substr(p_date, 1, 6), 'yyyymm'));    
  end;
  return l_date;

exception
   when others then
       Raise_Application_Error(-20001, 'Cannot convert "'||p_date||'"', TRUE);
end;

然后你应该在错误信息中看到错误的值。

如果您不想收到任何错误,可以使用此错误:

exception
   when others then
       RETURN NULL;

exception
   when others then
       RETURN SYSDATE;

然而,这更像是"我闭上眼睛以忽略错误"

相关问题