如何摆脱 PL/SQL 程序中的编译错误?
Posted
技术标签:
【中文标题】如何摆脱 PL/SQL 程序中的编译错误?【英文标题】:How to get rid of compilation error in PL/SQL procedure? 【发布时间】:2019-11-06 08:58:01 【问题描述】:作为 PL/SQL 的新手,我无法理解如何在过程中管理用户定义的异常。我的代码给出了警告'Procedure created with compiler errors'。
CREATE OR REPLACE PROCEDURE raise_salary
(eid IN employees.e_id%TYPE:=&emp_id,
raise IN employees.salary:=&salary_raise)
IS
cnt INTEGER;
salary employees.salary%TYPE;
BEGIN
SELECT count(*) INTO cnt FROM employees WHERE e_id=eid;
IF cnt=0 THEN
RAISE INVALID_ID;
ELSE
SELECT salary INTO sal FROM employees WHERE e_id=eid;
IF sal IS NULL THEN
RAISE NULL_VALUE;
ELSE
UPDATE employees SET salary=salary+raise WHERE e_id=eid;
dbms_output.put_line('Salary raised!');
END IF;
END IF;
EXCEPTION
WHEN INVALID_ID THEN
dbms_output.put_line('User ID does not exist!');
WHEN NULL_VALUE THEN
dbms_output.put_line('Salary is null in table!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
【问题讨论】:
好吧,我相信你在这个过程中有错误...... 有些开发工具会自动突出编译错误。您使用什么应用程序进行开发? 【参考方案1】:一个例子:
SQL> CREATE OR REPLACE PROCEDURE testException
2 IS
3 BEGIN
4 raise INVALID_ID;
5 EXCEPTION
6 WHEN INVALID_ID THEN
7 dbms_output.put_line('Invalid ID');
8 END;
9 /
Warning: Procedure created with compilation errors.
了解错误的方法:
SQL> sho err
Errors for PROCEDURE TESTEXCEPTION:
LINE/COL ERROR
-------- -----------------------------------------------------------------
0/0 PL/SQL: Compilation unit analysis terminated
4/5 PL/SQL: Statement ignored
4/11 PLS-00201: identifier 'INVALID_ID' must be declared
6/10 PLS-00201: identifier 'INVALID_ID' must be declared
你需要声明你使用的异常:
SQL> CREATE OR REPLACE PROCEDURE testException
2 IS
3 INVALID_ID exception;
4 BEGIN
5 raise INVALID_ID;
6 EXCEPTION
7 WHEN INVALID_ID THEN
8 dbms_output.put_line('Invalid ID');
9 END;
10 /
Procedure created.
【讨论】:
【参考方案2】:在DEMO 中,您将看到此 PROCEDURE 应处理的所有 3 种情况:
这是正确的程序:
CREATE OR REPLACE PROCEDURE raise_salary
(eid IN employees.e_id%TYPE,
raise IN employees.salary%type)
IS
cnt INTEGER;
sal employees.salary%TYPE;
INVALID_ID exception;
NULL_VALUE exception;
BEGIN
SELECT count(*)
INTO cnt
FROM employees
WHERE e_id=eid;
IF cnt=0 THEN
RAISE INVALID_ID;
ELSE
SELECT salary
INTO sal
FROM employees
WHERE e_id=eid;
IF sal IS NULL THEN
RAISE NULL_VALUE;
ELSE
UPDATE employees
SET salary = (SAL + raise)
WHERE e_id = eid;
dbms_output.put_line('Salary raised!');
END IF;
END IF;
exception
WHEN INVALID_ID THEN
dbms_output.put_line('User ID does not exist!');
WHEN NULL_VALUE THEN
dbms_output.put_line('Salary is null in table!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
您有不止一个错误,@Aleksej 在他的回答 VOTE UP 中很好地解释了一个错误。 你还有一行:
SELECT salary INTO sal FROM employees WHERE e_id=eid;
但是你还没有声明sal。 希望这会有所帮助...
【讨论】:
以上是关于如何摆脱 PL/SQL 程序中的编译错误?的主要内容,如果未能解决你的问题,请参考以下文章