我是PL / SQL和Oracle的新手。我正在处理一个小代码块,它会在列中生成前5个值。当表中的数据少于5行时,我试图获取异常。
DELETE FROM CREDIT_CARD;
SELECT * FROM CREDIT_CARD;
Insert into CREDIT_CARD values (6011956844573649,'550',892);
Insert into CREDIT_CARD values (5250335443644204,'15000',661);
DECLARE
CURSOR Final_Q2_Cursor is
SELECT CREDITCARDNUMBER,CREDITCARDLIMIT,CUSTOMERID FROM CREDIT_CARD
ORDER BY CREDITCARDLIMIT DESC; -- start with highest paid employee
aCardLimt NUMBER(8,2);
aCardNum NUMBER(16);
aCustId INT;
BEGIN
OPEN Final_Q2_Cursor ;
FOR i IN 1..5 LOOP
FETCH Final_Q2_Cursor INTO aCardNum, aCardLimt, aCustId;
EXIT WHEN Final_Q2_Cursor%NOTFOUND;
INSERT INTO TOP_FIVE_CREDIT_LIMITS VALUES (aCardLimt, aCardNum, aCustId);
END LOOP;
CLOSE Final_Q2_Cursor;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
我只插入2行数据,但它仍在处理所有内容。为什么呢?
答案 0 :(得分:0)
以下是您询问游标属性以确定是否需要显式引发错误的示例
SQL> create table TOP_FIVE_CREDIT_LIMITS (CREDITCARDLIMIT int, CREDITCARDNUMBER int, CUSTOMERID int );
Table created.
SQL> create table CREDIT_CARD (
2 CREDITCARDNUMBER int,CREDITCARDLIMIT int,CUSTOMERID int );
Table created.
SQL>
SQL> DELETE FROM CREDIT_CARD;
0 rows deleted.
SQL> SELECT * FROM CREDIT_CARD;
no rows selected
SQL> Insert into CREDIT_CARD values (6011956844573649,'550',892);
1 row created.
SQL> Insert into CREDIT_CARD values (5250335443644204,'15000',661);
1 row created.
SQL>
PL / SQL:
SQL> set serverout on
SQL> DECLARE
2 CURSOR Final_Q2_Cursor is
3 SELECT CREDITCARDNUMBER,CREDITCARDLIMIT,CUSTOMERID FROM CREDIT_CARD
4 ORDER BY CREDITCARDLIMIT DESC; -- start with highest paid employee
5
6 aCardLimt NUMBER(8,2);
7 aCardNum NUMBER(16);
8 aCustId INT;
9 BEGIN
10 OPEN Final_Q2_Cursor ;
11 FOR i IN 1..5 LOOP
12 FETCH Final_Q2_Cursor INTO aCardNum, aCardLimt, aCustId;
13
14 if Final_Q2_Cursor%NOTFOUND and i < 5 then
15 raise_application_error(-20000,'Ran out of rows before I got to 5');
16 end if;
17 EXIT WHEN Final_Q2_Cursor%NOTFOUND;
18 INSERT INTO TOP_FIVE_CREDIT_LIMITS VALUES (aCardLimt, aCardNum, aCustId);
19 END LOOP;
20 CLOSE Final_Q2_Cursor;
21 EXCEPTION
22 WHEN no_data_found THEN
23 dbms_output.put_line('No such customer!');
24 WHEN others THEN
25 dbms_output.put_line('Error!');
26 END;
27 /
Error!
PL/SQL procedure successfully completed.
但我强调,这不是一种聪明的做事方式(虽然如果你的任务......那很好)。通常我们会尽可能地使用SQL来保持代码的良好和精益,并且我们从不喜欢在其他时间捕获所有错误而不将它们传播回调用环境。所以你也可以重新编写你的代码,如下所示:
SQL> set serverout on
SQL> BEGIN
2 insert into TOP_FIVE_CREDIT_LIMITS
3 select *
4 from
5 ( SELECT CREDITCARDNUMBER,CREDITCARDLIMIT,CUSTOMERID FROM CREDIT_CARD
6 ORDER BY CREDITCARDLIMIT DESC
7 )
8 where rownum <= 5;
9
10 if sql%rowcount = 0 then
11 raise_application_error(-20000,'No rows were found at all');
12 elsif sql%rowcount < 5 then
13 raise_application_error(-20000,'Ran out of rows before I got to 5');
14 end if;
15
16 END;
17 /
BEGIN
*
ERROR at line 1:
ORA-20000: Ran out of rows before I got to 5
ORA-06512: at line 13