PL/SQL块问题:找不到数据错误 [英] PL/SQL block problem: No data found error

查看:106
本文介绍了PL/SQL块问题:找不到数据错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SET SERVEROUTPUT ON
DECLARE
    v_student_id NUMBER := &sv_student_id;
    v_section_id NUMBER := 89;
    v_final_grade NUMBER;
    v_letter_grade CHAR(1);
BEGIN
    SELECT final_grade
    INTO v_final_grade
    FROM enrollment
    WHERE student_id = v_student_id
    AND section_id = v_section_id;

    CASE -- outer CASE
        WHEN v_final_grade IS NULL THEN
            DBMS_OUTPUT.PUT_LINE ('There is no final grade.');
        ELSE
            CASE -- inner CASE
                WHEN v_final_grade >= 90 THEN v_letter_grade := 'A';
                WHEN v_final_grade >= 80 THEN v_letter_grade := 'B';
                WHEN v_final_grade >= 70 THEN v_letter_grade := 'C';
                WHEN v_final_grade >= 60 THEN v_letter_grade := 'D';
                ELSE v_letter_grade := 'F';
            END CASE;

            -- control resumes here after inner CASE terminates
            DBMS_OUTPUT.PUT_LINE ('Letter grade is: '||v_letter_grade);
    END CASE;
    -- control resumes here after outer CASE terminates
END;

我从《 em的Oracle PL/SQL示例,第4版2009》中摘录的上述代码我的问题是,当我输入表中不存在的student_id时,它返回给我跟随错误

the above code I have taken from the book "Oracle PL/SQL by Example, 4th Edition 2009" my problem is when I enter a student_id not present in the table it returns me the following error


Error report: ORA-01403: no data found
ORA-06512: at line 7
01403. 00000 -  "no data found"
*Cause:    
*Action:

但根据这本书,它应该返回一个空值,然后按照案例流程进行操作.

but according to the book it should have returned a null value and then follow the case flow.

推荐答案

当您选择INTO变量且没有返回记录时,您将收到无数据发现"错误.我相信编写上述代码的正确方法是使用其自己的BEGIN/EXCEPTION/END块包装SELECT语句.示例:

When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block. Example:

...
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN

    BEGIN
    SELECT final_grade
      INTO v_final_grade
      FROM enrollment
     WHERE student_id = v_student_id
       AND section_id = v_section_id;

    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        v_final_grade := NULL;
    END;

    CASE -- outer CASE
      WHEN v_final_grade IS NULL THEN
      ...

这篇关于PL/SQL块问题:找不到数据错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆