我正在尝试创建一个代码,我通过指定他的nr_matr从我的表中删除一个学生,但是如果我在我的表中没有那个nr_matr那么我想要抛出异常。 这是我的代码:
-Match
当我试图编译我的代码时,它表示包体是由编译错误创建的。我做错了什么?
答案 0 :(得分:0)
错误为PLS-00201: identifier 'COUNTER' must be declared
,您可以在尝试编译程序包主体后运行SHOW ERRORS;
来查找错误。
你可以这样解决:
CREATE OR REPLACE PACKAGE BODY manager_faculty IS
PROCEDURE delete_stud (nr_matr student.nr_matricol%type)
IS
counter INT;
BEGIN
DELETE FROM student
WHERE nr_matricol=nr_matr;
EXCEPTION
WHEN no_data_found THEN
SELECT COUNT(*)
INTO counter
FROM student
WHERE nr_matricol=nr_matr;
IF counter = 0 THEN
raise_application_error (
-20001,
'There is no student with the number' || nr_matr
);
END IF;
END delete_stud;
END manager_faculty;
/
SHOW ERRORS;
但是,代码不会按预期运行,因为DELETE FROM
如果不删除任何行,则不会抛出异常。您需要检查SQL%ROWCOUNT
:
CREATE OR REPLACE PACKAGE BODY manager_faculty IS
PROCEDURE delete_stud (nr_matr student.nr_matricol%type)
IS
BEGIN
DELETE from student
WHERE nr_matricol=nr_matr;
IF SQL%ROWCOUNT = 0 THEN
raise_application_error (
-20001,
'There is no student with the number' || nr_matr
);
END IF;
END delete_stud;
END manager_faculty;
/
答案 1 :(得分:0)
除了使用MTO所回答的SQL%ROWCOUNT之外,您还可以使用SQL%NOTFOUND。
如果INSERT,UPDATE或DELETE语句不影响任何行,或者SELECT INTO语句未返回任何行,则%NOTFOUND 会产生TRUE。否则,它会产生FALSE。
CREATE OR REPLACE PACKAGE BODY manager_faculty IS
PROCEDURE delete_stud (nr_matr student.nr_matricol%type)
IS
BEGIN
DELETE from student
WHERE nr_matricol=nr_matr;
IF SQL%NOTFOUND THEN
raise_application_error (
-20001,
'There is no student with the number' || nr_matr
);
END IF;
END delete_stud;
END manager_faculty;
如果您想了解SQL Cursor的其他属性,可以阅读here。