PLSQL没有正确引发异常的函数

时间:2016-04-21 21:05:45

标签: oracle function plsql exception-handling

我正在编写一个函数,用于在输入ID时返回学生的姓名。如果输入的ID在数据库中不存在,我想要引发异常。相反,当我输入不正确的学生ID时,如果我抛出基本异常,则返回任何内容,或者返回此错误消息并声明异常:

6503. 00000 -  "PL/SQL: Function returned without value"
*Cause:    A call to PL/SQL function completed, but no RETURN statement was
       executed.
*Action:   Rewrite PL/SQL function, making sure that it always returns
       a value of a proper type.

这是我的功能:

CREATE OR REPLACE Function STUDENT( S_NUM IN NUMBER)
RETURN varchar2 IS
STUDENT_NAME varchar2(50);
NOTEXISTS   EXCEPTION;
   cursor S_CUR is
   SELECT S_NAME
      FROM ROSTER
      WHERE S_NUM = S_ID;
BEGIN
   open S_CUR;
   fetch S_CUR into STUDENT_NAME;

   if S_CUR%notfound then
      RAISE NOTEXISTS;
   end if;
   close S_CUR;
RETURN STUDENT_NAME;

EXCEPTION
WHEN NOTEXISTS THEN -- handle the error
      dbms_output.put_line('NO STUDENT FOUND.');
END;

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

发生异常时,您不会返回实际的错误消息。您的函数应该返回varchar。但是,您只是打印错误而不返回实际的错误消息。

EXCEPTION
WHEN NOTEXISTS THEN -- handle the error
      dbms_output.put_line('NO STUDENT FOUND.');
      return 'No Student Found'
END;

答案 1 :(得分:2)

首先,不要定义自己只在函数上下文中有效的异常,而是使用为这种情况定义的标准异常 - NO_DATA_FOUND异常:

CREATE OR REPLACE Function STUDENT(S_NUM IN ROSTER.S_ID%TYPE)
    -- Exceptions: raises NO_DATA_FOUND if the student ID passed in
    --             parameter S_NUM is not found in the STUDENT table.
    RETURN ROSTER.S_NAME%TYPE
IS
  STUDENT_NAME ROSTER.S_NAME%TYPE;
  bData_found  BOOLEAN;

 CURSOR S_CUR IS
   SELECT S_NAME
      FROM ROSTER
      WHERE S_NUM = S_ID;
BEGIN
  OPEN S_CUR;

  FETCH S_CUR INTO STUDENT_NAME;

  bData_found := S_CUR%NOTFOUND;

  CLOSE S_CUR;

  IF bData_found THEN
    RETURN STUDENT_NAME;    
  ELSE
    RAISE NO_DATA_FOUND;
  END IF;
END STUDENT;

其次,不要在函数中处理异常。异常的目的是允许代码将异常条件传递给其他代码。让调用者处理异常,如:

DECLARE
  nStudent_id      ROSTER.S_ID%TYPE := 12345;
  strStudent_name  ROSTER.S_NAME%TYPE;
BEGIN
  strStudent_name := STUDENT(nStudent_id);
  DBMS_OUTPUT.PUT_LINE('S_ID=' || nStudent_id || '  NAME=' || strStudent_name);
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('NO STUDENT FOUND.');
END;

祝你好运。