随笔 - 13, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

实例演示有关Oracle中的约束

先创建一个表,表示学习的专业:

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;

posted on 2009-06-02 00:02 五味杂陈 阅读(331) 评论(0)  编辑 收藏 引用 所属分类: Oracle


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理