先创建一个表,表示学习的专业:
Create TABLE major
(ID number(3),
majorName nvarchar2(30));
然后对这个表增加各种约束
ALTER TABLE major ADD CONSTRAINTS pk_major PRIMARY KEY(ID); --主键约束
ALTER TABLE major MODIFY majorName CONSTRAINTS nn_majorName NOT NULL; --非空约束
ALTER TABLE major ADD CONSTRAINTS ck_majorID CHECK(ID<200); --Check约束
ALTER TABLE major MODIFY majorName CONSTRAINTS un_majorName UNIQUE; --唯一约束
重命名Constraint
ALTER TABLE major RENAME CONSTRAINT un_majorName TO un_major;
再创建一个学生表,在创建的同时增加各种约束
Create TABLE student
(studentID number(10) CONSTRAINTS pk_student PRIMARY KEY, --主键约束
ID number(20) CONSTRAINTS un_id UNIQUE,--唯一约束
studentName nvarchar2(30) CONSTRAINTS nn_name NOT NULL, --非空约束
majorId number(3) CONSTRAINTS fk_major_student REFERENCES major(ID) ON DELETE CASCADE,--外键约束
sex nvarchar2(1) DEFAULT 'M' CONSTRAINTS nn_sex NOT NULL,--默认值,非空约束
CONSTRAINTS ck_sex CHECK((sex='M') OR (sex='F')), --Check约束
birthDate date,
birthPlace number(6));
将外键删除
ALTER TABLE student DROP CONSTRAINTS fk_major_student;
然后添加外键
ALTER TABLE student ADD CONSTRAINTS fk_major_student FOREIGN KEY(majorID)
REFERENCES major(ID) ON DELETE CASCADE;
然后演示将所有约束删除:
ALTER TABLE student DROP CONSTRAINTS pk_student ;
ALTER TABLE student DROP CONSTRAINTS un_id ;
ALTER TABLE student DROP CONSTRAINTS nn_name ;
ALTER TABLE student DROP CONSTRAINTS fk_major_student;
ALTER TABLE student DROP CONSTRAINTS nn_sex;
ALTER TABLE student DROP CONSTRAINTS ck_sex;