PL / SQL - 没有找到数据错误

时间:2014-02-27 06:20:56

标签: oracle for-loop plsql indexing

当我尝试运行以下块时,我收到此错误“ORA-01403:找不到数据”。

SET SERVEROUTPUT ON

DECLARE
  TYPE dept_table_type IS TABLE OF departments.department_name%TYPE
  INDEX BY PLS_INTEGER;
  my_dept_table dept_table_type;
  f_loop_count NUMBER(2) :=10;
  v_deptno NUMBER(5) :=0;
BEGIN
  FOR i IN 1..f_loop_count LOOP
      v_deptno := v_deptno + 10;
    SELECT department_name
    INTO my_dept_table(i)
    FROM departments
    WHERE department_id = v_deptno;
  END LOOP;
  FOR i IN 1..f_loop_count LOOP
    DBMS_OUTPUT.PUT_LINE(my_dept_table(i));
  END LOOP;
END;
/

我对这个问题不是100%肯定。我唯一能想到的是在DECLARE块中它没有正确地执行INDEX部分 - 尽管我不确定如何让它工作。

干杯

1 个答案:

答案 0 :(得分:0)

Oracle,当看到无数据的Selected查询,并且您尝试将其放入变量时,最终会抛出异常。因为,INTO变量现在保持不变,开发人员必须相应地处理它!

DECLARE
  TYPE dept_table_type IS TABLE OF departments.department_name%TYPE
  INDEX BY PLS_INTEGER;
  my_dept_table dept_table_type;
  f_loop_count NUMBER(2) :=10;
  v_deptno NUMBER(5) :=0;
BEGIN
  FOR i IN 1..f_loop_count LOOP
      v_deptno := v_deptno + 10;
      BEGIN
        SELECT department_name
        INTO my_dept_table(i)
        FROM departments
        WHERE department_id = v_deptno;
      EXCEPTION WHEN NO_DATA_FOUND THEN
         DBMS_OUTPUT.PUT_LINE('No Data for ' || v_deptno);
         my_dept_table(i) := NULL;
         --Flow continues
      END;
  END LOOP;
  FOR i IN 1..f_loop_count LOOP
    DBMS_OUTPUT.PUT_LINE(my_dept_table(i));
  END LOOP;
END;
/