在SQL表创建过程中是否还有其他方法可以创建约束?

时间:2012-02-01 03:41:16

标签: sql oracle

假设我有以下SQL语句,使用Oracle:

drop table department cascade constraints;
drop table facultyStaff cascade constraints;
drop table student cascade constraints;
drop table campusClub cascade constraints;
drop table studentClub cascade constraints;

create table department 
(   code      varchar2(3) primary key,
    name      varchar2(40)  not null,
    chair     varchar2(11));

create table facultyStaff 
(   staffID     varchar2(5) primary key,
    dob     date,
    firstName   varchar2(20),
    lastName    varchar2(20),
    rank        varchar2(10),
    deptCode    varchar2(3),
    constraint rankValue check (rank in ('Assistant', 'Associate', 'Full', 'Emeritus')),
    constraint facultyDeptFk foreign key (deptCode) references department (code));

create table student 
(   studentId   varchar2(5) primary key,
    dob     date ,
    firstName   varchar2(20),
    lastName    varchar2(20),
    status      varchar(10),
    major       varchar(3),
constraint statusValue check (status in ('Freshman', 'Sophomore', 'Junior', 'Senior',  'Graduate')),
    constraint studentMajorFk foreign key (major) references department (code));

alter table department 
    add constraint departmentChairFk foreign key(chair) references facultyStaff(staffId) on delete set null; 

由于主席与教职员之间存在主席关系的递归参考,因此在定义教师表之前,无法定义部门主席的外键约束。在使用alter table语句定义faculty之后,必须添加约束。

有没有其他方法可以做到这一点,以某种方式自动化约束创建,从而消除alter table语句?

1 个答案:

答案 0 :(得分:4)

您可以使用create schema声明执行此操作:

create schema authorization [schema name]
create table department 
(   code      varchar2(3) primary key,
    name      varchar2(40)  not null,
    chair     varchar2(11),
    constraint departmentChairFk foreign key(chair) references facultyStaff(staffId) on delete set null
)
create table facultyStaff 
(   staffID     varchar2(5) primary key,
    dob     date,
    firstName   varchar2(20),
    lastName    varchar2(20),
    rank        varchar2(10),
    deptCode    varchar2(3),
    constraint rankValue check (rank in ('Assistant', 'Associate', 'Full', 'Emeritus')),
    constraint facultyDeptFk foreign key (deptCode) references department (code)
)
create table student 
(   studentId   varchar2(5) primary key,
    dob     date ,
    firstName   varchar2(20),
    lastName    varchar2(20),
    status      varchar(10),
    major       varchar(3),
constraint statusValue check (status in ('Freshman', 'Sophomore', 'Junior', 'Senior',  'Graduate')),
    constraint studentMajorFk foreign key (major) references department (code)
);