SQL INSERT INTO子实体

时间:2018-05-13 17:50:32

标签: sql oracle

我有两个实体,一个父EMPLOYEE表和一个子DOCTOR表,如下所示:

CREATE TABLE EMPLOYEE(
Emp_Id VARCHAR2(3 CHAR) CONSTRAINT employee_emp_id PRIMARY KEY,
Emp_Fname VARCHAR2(20 CHAR) NOT NULL,
Emp_Lname VARCHAR2(20 CHAR) NOT NULL,
Emp_DOB DATE NOT NULL,
Emp_Address VARCHAR2(40 CHAR),
Emp_Phone VARCHAR2(10 CHAR) NOT NULL,
Emp_Email VARCHAR2(40 CHAR) NOT NULL,
Emp_Type VARCHAR2(1 CHAR) check (Emp_Type in ('D', 'N', 'R')));

CREATE TABLE DOCTOR(
Doc_Id VARCHAR2(3 CHAR) CONSTRAINT doctor_doc_id PRIMARY KEY,
Emp_Id VARCHAR2(3 CHAR) REFERENCES EMPLOYEE(emp_id),
Doc_Spec VARCHAR2(10 CHAR) NOT NULL, 
Doc_Med_Lic VARCHAR2(10 CHAR) NOT NULL, 
Doc_Fee NUMBER(10,2) NOT NULL, 
Doc_Avail VARCHAR2(3 CHAR) check(Doc_Avail in ('Yes'/'No')));

如何将行插入DOCTOR表,以便将其输入EMPLOYEE表,或者至少引用EMPLOYEE表中的现有条目?将行插入EMPLOYEE表非常简单:

INSERT INTO EMPLOYEE (Emp_Id, Emp_Fname, Emp_Lname, Emp_DOB, Emp_Address, Emp_Phone, Emp_Email, Emp_Type)
VALUES (emp_id_no_seq.NEXTVAL,'John', 'Le Grange', '15-MAY-65','15 Maple Ave.', '0112562314', 'jlg@rockhealth.com', 'D');

我对子实体的关系INSERT INTO有点模糊。任何帮助清除这一点或引用我解决这个问题的线程将不胜感激。

1 个答案:

答案 0 :(得分:0)

由于DOCTOR引用EMPLOYEE,您必须先在员工表中添加一行,然后使用员工ID向医生插入一行。如果您在PL / SQL中执行此操作,那么RETURNING INTO子句就足够了,它返回实际插入表中的值:

DECLARE
    l_id    employee.id%TYPE;
BEGIN
    INSERT INTO employee ( id, ... )
    VALUES ( emp_id_no_seq.NEXTVAL, ... )
    RETURNING id INTO l_id;

    INSERT INTO doctor ( id, emp_id, ... )
    VALUES ( doc_id_so_seq.NEXTVAL, l_emp_id, ... );
END;