2

我正在尝试编写一个有 2 个异常错误的存储过程。

Create table Employee 
(emp_num varchar(10) primary key, 
emp_name varchar(10),
DOB date,
job_title varchar(15),
marriage_date date,
spouseid varchar(10) references Employee(emp_num),
dept_id varchar(10) references Department(dept_id));

如您所见,这是一张包含员工信息的表格。这里有一个递归关系,如果配偶也是公司的雇员,则需要提供配偶信息(spouseid+marriage_date)。我创建了一个存储过程,它询问员工编号并为您提供配偶、姓名和结婚日期。

CREATE OR REPLACE PROCEDURE DISP_SPOUSE
(SP_EMP_NUM IN EMPLOYEE.EMP_NUM%TYPE) AS
SP_NAME EMPLOYEE.EMP_NAME%TYPE;
SP_SPOUSEID EMPLOYEE.SPOUSEID%TYPE;
SP_MARRIAGE_DATE EMPLOYEE.MARRIAGE_DATE%TYPE;

BEGIN
SELECT SPOUSEID, EMP_NAME, MARRIAGE_DATE
INTO SP_SPOUSEID, SP_NAME, SP_MARRIAGE_DATE
FROM EMPLOYEE
WHERE EMP_NUM = SP_EMP_NUM;

DBMS_OUTPUT.PUT_LINE ((SP_SPOUSEID)||' '||
(SP_NAME)||' '||(SP_MARRIAGE_DATE));
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO EMPLOYEE WITH THAT NUMBER:'||SP_EMP_NUM);

END;
/

我还需要添加第二个用户定义的异常,如果没有配偶,则会引发该异常。所以我在想这样的事情:

DECLARE
SP_EXCEPTION EXCEPTION;
PRAGMA EXCEPTION_INIT (SP_EXCEPTION, -20001);
BEGIN
RAISE_APPLICATION_ERROR (-20001, 'NO EMPLOYEE SPOUSE');
EXCEPTION
WHEN SP_EXCEPTION
THEN
DBMS_OUTPUT.PUT_LINE ( SQLERRM );
END;
/

然后在存储过程代码中添加第二个异常(在 no_data_found 异常之后或之前:

WHEN SPOUSEID IS NULL
RAISE SP_EXCEPTION;

end;
/

我在配偶 ID = null 上有问题。有不同的写法吗?(插入到配偶ID 中的某些值确实为空)。

4

1 回答 1

2

没关系,我解决了。

CREATE OR REPLACE PROCEDURE DISP_SPOUSE
(SP_EMP_NUM IN EMPLOYEE.EMP_NUM%TYPE) AS
SP_NAME EMPLOYEE.EMP_NAME%TYPE;
SP_SPOUSEID EMPLOYEE.SPOUSEID%TYPE;
SP_MARRIAGE_DATE EMPLOYEE.MARRIAGE_DATE%TYPE;

SP_EXCEPTION EXCEPTION;


BEGIN

SELECT SPOUSEID, EMP_NAME, MARRIAGE_DATE
INTO SP_SPOUSEID, SP_NAME, SP_MARRIAGE_DATE
FROM EMPLOYEE
WHERE EMP_NUM = SP_EMP_NUM;

IF 
SP_SPOUSEID IS NULL THEN
RAISE SP_EXCEPTION;


ELSE
DBMS_OUTPUT.PUT_LINE ((SP_SPOUSEID)||' '||
(SP_NAME)||' '||(SP_MARRIAGE_DATE));

END IF;

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
('NO EMPLOYEE WITH THAT NUMBER:'||SP_EMP_NUM);
WHEN SP_EXCEPTION THEN
DBMS_OUTPUT.PUT_LINE ('NO SPOUSE AS EMPLOYEE');
END;
/
于 2013-05-04T01:53:18.780 回答