找不到匹配的记录时返回NULL

Rag*_*gav 0 oracle plsql function

我正在将一个员工编号传递给一个函数并返回加入日期.

我希望在找不到匹配的记录时返回NULL; 在我的情况下,它只是返回空白或空行;

get_join_date(in_emp_no)

CREATE OR REPLACE FUNCTION get_join_date(in_emp_no) RETURN DATE IS
  v_join_date DATE;
  BEGIN
    SELECT joined_date
    INTO v_date
    FROM employee
    WHERE employee_number = in_emp_no
          AND type = in_type;

    IF v_join_date IS NOT NULL        THEN
      v_join_date := v_date;
    ELSE
      v_join_date = NULL;
    END IF;

    RETURN v_join_date;
  END;
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 5

如果未找到匹配的记录,则会引发NO_DATA_FOUND异常; 你必须捕获这个异常并返回一些东西.

您还要检查是否v_join_date为null,如果为null,则为其分配空值; 没有必要这样做.

create or replace function get_join_date( 
      Pemp_no in number
     ) return date is

   l_join_date date;

begin

   select joined_date into l_join_date 
     from employee
    where employee_number = Pemp_no
      and type = in_type;

   return l_join_date;

exception when no_data_found then
   return null;

end;
Run Code Online (Sandbox Code Playgroud)

其他错误包括:

  1. 您正在选择,v_date但您已将变量声明为v_join_date
  2. 你的end陈述后没有分号.
  3. 你的endif陈述后没有分号.
  4. endif 是两个字,这应该是 end if;
  5. 例如,您没有声明所需参数的数据类型in_emp_no(但不是长度)... function get_join_date ( Pemp_no number ) ...