使用循环引用创建表

时间:2013-09-16 16:07:39

标签: sql oracle circular-reference

如何使用循环引用创建多个表。我有这个数据,我想一次性创建:

DROP TABLE employee CASCADE CONSTRAINTS;
CREATE TABLE employee (
  fname    varchar2(15) not null, 
  minit    varchar2(1),
  lname    varchar2(15) not null,
  ssn      char(9),
  bdate    date,
  address  varchar2(30),
  sex      char,
  salary   number(10,2),
  superssn char(9),
  dno      number(4),
  primary key (ssn),
  foreign key (superssn) references employee(ssn),
  foreign key (dno) references department(dnumber)
);

DROP TABLE department CASCADE CONSTRAINTS;
CREATE TABLE department (
  dname        varchar2(15) not null,
  dnumber      number(4),
  mgrssn       char(9) not null, 
  mgrstartdate date,
  primary key (dnumber),
  unique (dname),
  foreign key (mgrssn) references employee(ssn)
);

DROP TABLE dept_locations CASCADE CONSTRAINTS;
CREATE TABLE dept_locations (
  dnumber   number(4),
  dlocation varchar2(15), 
  primary key (dnumber,dlocation),
  foreign key (dnumber) references department(dnumber)
);

DROP TABLE project CASCADE CONSTRAINTS;
CREATE TABLE project (
  pname      varchar2(15) not null,
  pnumber    number(4),
  plocation  varchar2(15),
  dnum       number(4) not null,
  primary key (pnumber),
  unique (pname),
  foreign key (dnum) references department(dnumber)
);

DROP TABLE works_on CASCADE CONSTRAINTS;
CREATE TABLE works_on (
  essn   char(9),
  pno    number(4),
  hours  number(4,1),
  primary key (essn,pno),
  foreign key (essn) references employee(ssn),
  foreign key (pno) references project(pnumber)
);

DROP TABLE dependent CASCADE CONSTRAINTS;
CREATE TABLE dependent (
  essn           char(9),
  dependent_name varchar2(15),
  sex            char,
  bdate          date,
  relationship   varchar2(8),
  primary key (essn,dependent_name),
  foreign key (essn) references employee(ssn)
);

请帮助!!

1 个答案:

答案 0 :(得分:6)

您可以创建表格然后创建约束:

CREATE TABLE employee (
  fname    varchar2(15) not null, 
  minit    varchar2(1),
  lname    varchar2(15) not null,
  ssn      char(9),
  bdate    date,
  address  varchar2(30),
  sex      char,
  salary   number(10,2),
  superssn char(9),
  dno      number(4),
  primary key (ssn)
);

CREATE TABLE department (
  dname        varchar2(15) not null,
  dnumber      number(4),
  mgrssn       char(9) not null, 
  mgrstartdate date,
  primary key (dnumber),
  unique (dname)
);

ALTER TABLE employee ADD CONSTRAINT fk_dno FOREIGN KEY (dno) REFERENCES department(dnumber) DEFERRABLE;
ALTER TABLE department ADD CONSTRAINT fk_mgrssn FOREIGN KEY (mgrssn) REFERENCES employee(ssn) DEFERRABLE;

插入时,您可以设置延迟约束,这意味着Oracle在您提交之前不会验证它们。

ALTER SESSION SET CONSTRAINTS = DEFERRED;
insert into employee (fname, lname, ssn, dno) values ('Joe','Blow','123456789', 10);
insert into department(dname, dnumber, mgrssn) values ('Dept1',10, '123456789');
commit;

您也可以在创建时将它们设置为最初延迟,但约束必须至少“可延迟”才能执行上述操作。