gpt4 book ai didi

sql - 在 SQL 表创建过程中还有其他方法可以创建约束吗?

转载 作者:行者123 更新时间:2023-12-04 14:36:00 26 4
gpt4 key购买 nike

假设我有以下 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;

由于department和faculty之间存在chair关系的递归引用,所以department中chair的外键约束只有在faculty表定义后才能定义。必须在使用 alter table 语句定义 faculty 之后添加约束。

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

最佳答案

您可以使用 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)
);

关于sql - 在 SQL 表创建过程中还有其他方法可以创建约束吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9090431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com