我想在查询未获取任何记录时引发自定义错误。但是下面的代码没有抛出我想要的错误。它引发系统生成错误。请你帮助我好吗?我在犯什么错误?
DECLARE
v_em_id NUMBER := &var_id;
v_name varchar2(20);
BEGIN
SELECT first_name INTO v_name FROM employees WHERE employee_id =v_em_id;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20002,'Employee not exist');
END IF;
DBMS_OUTPUT.PUT_LINE('Hi! '|| v_name);
END;
我应该抛出错误代码:-20002 和错误消息:员工不存在。
答案 0 :(得分:2)
您可以尝试以下代码...
<a href="series-1.html" class="s1">Series 1
<div class="images">
<div class="image1">
<img src="image1.jpg">
</div>
<div class="image2">
<img src="image2.jpg">
</div>
</div>
</a>
<a href="series-2.html" class="s2">Series 2
<div class="images">
<div class="image1">
<img src="bowl.jpg">
</div>
<div class="image2">
<img src="octupus.jpg">
</div>
</div>
</a>
如果DECLARE
v_em_id NUMBER := &var_id;
v_name varchar2(20);
BEGIN
SELECT first_name INTO v_name FROM employees WHERE employee_id = v_em_id;
DBMS_OUTPUT.PUT_LINE('Hi! ' || v_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Employee not exist');
END IF;
END;
语句不返回任何行,它将引发select
异常。因此,系统在no_data_found
行之前失败了。
答案 1 :(得分:0)
SQL%NOTFOUND
在这里没有用。如果未找到任何内容,则会引发NO_DATA_FOUND
异常,因此您必须处理该异常。这是一个基于Scott模式的示例:
SQL> declare
2 v_em_id number := &empno;
3 v_name varchar2(20);
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_em_id;
9
10 dbms_output.put_line('Hi, ' || v_name);
11 exception
12 when no_data_found then
13 raise_application_error(-20002, 'Employee does not exist');
14 end;
15 /
Enter value for empno: 7934
Hi, MILLER
PL/SQL procedure successfully completed.
SQL> /
Enter value for empno: 111
declare
*
ERROR at line 1:
ORA-20002: Employee does not exist
ORA-06512: at line 13
SQL>