函数返回没有值06503

时间:2014-01-24 12:56:13

标签: oracle plsql

我有这个功能只返回不正确的数据,但我收到此错误信息

当我运行查询时,

“返回没有值的函数”。

功能

CREATE OR REPLACE FUNCTION date_chk(p_value VARCHAR2, p_format VARCHAR2)
RETURN NUMBER
AS
  v_val1 NUMBER(10);
  v_date DATE;
BEGIN
  v_date := TO_DATE(p_value,p_format);
  RETURN 1;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE = -01858 THEN
      RETURN 0;
    END IF;
END;

查询

SELECT sid,
       sid,
       sentry,
       daytime
FROM test_table

WHERE date_chk(白天,'HH24:MI')= 0;

被修改

例如,如果白天有类似09:99的内容,则会显示此错误消息,但如果是abshaasj,则会返回这些值。如果在我的任何记录中找到任何数字和字母,我试图返回数字和字母。我有10345条记录,其中很多都是返回时间格式。

2 个答案:

答案 0 :(得分:2)

你必须在这里放一些东西:

EXCEPTION
WHEN OTHERS THEN
  IF SQLCODE = -01858 THEN
   RETURN 0;
  ELSE             -- > Missing in your code
   RETURN SQLCODE; -- > Missing in your code
  END IF;
END;

答案 1 :(得分:1)

如果你想检查作为字符文字提供的日期时间信息的正确性,那么除了ORA-01858之外,你还可以获得许多其他异常,这取决于日期时间值或/和格式的不正确性。当然,您可以编写尽可能多的IF条件,或者更好的是,通过使用exception_init()编译指示将异常名称与异常编号相关联,因为可能会引发许多异常,或者您可以声明一个例外,比如wrong_date_time并抓住它,如下所示:

create or replace package pkg1 as
  function date_chk(p_value in varchar2, p_format in varchar2) return number;
end;

create or replace package body pkg1 as
  -- This function is simply trying to convert character literal to a value of 
  -- date data type. If it's not possible for whatever reason it raises 
  -- user defined ORA-20001 exception. We will catch it later.
  function to_date1( p_value in varchar2, p_format in varchar2) return date is
  begin
    -- Here we add fx modifier to require exact matching between
    -- character literal and format model, otherwise
    -- something like 21.01 will give us 1, which is not quite correct.
    return to_date(p_value, concat('fx',p_format)); 
  exception
    when others then raise_application_error(-20001, 'wrong date');
  end;

  function date_chk(p_value in varchar2, p_format in varchar2) return number is
    wrong_date_time exception;
    pragma exception_init(wrong_date_time, -20001);
    l_res date;
  begin
    l_res := pkg1.to_date1(p_value, p_format);
    return 1;
  exception
    when wrong_date_time then
      return 0;
  end;
end;

测试用例:

SQL> select pkg1.date_chk('09:99', 'hh24:mi') as res
  2    from dual
  3  ;
       RES
----------
         0

SQL> select pkg1.date_chk('09:59', 'hh24:mi') as res
  2    from dual
  3  ;
       RES
----------
         1

SQL> select pkg1.date_chk('asdas', 'hh24:mi') as res
  2    from dual
  3  ;
       RES
----------
         0