你好,游客 登录 注册 搜索
背景:
阅读新闻

Oracle数据库的字段约束创建和维护

[日期:2013-10-02] 来源:Linux社区  作者:facekbook [字体:大 中 小]

创建Oracle数据库的字段约束:

非空约束
唯一约束
对字段的取值的约束
默认值
外键约束

create table tab_class(
 class_id number primary key,
 class_name varchar2(10) not null unique
);

create table tab_stu(
stu_id number,
 --学生姓名,不能为空,不能重复
stu_name varchar2(20) not null unique,
 --学生姓名只能是male或female
stu_gender varchar2(6) not null check(stu_gender='male' or stu_gender='female'),
 --学生年龄只能在18到60之间
stu_age number check(stu_age >18 and stu_age <60),
 --邮箱可以不填写,填写的话不能相同
stu_email varchar2(30) unique,
stu_address varchar2(30),
--外键约束
class_id number not null references tab_class(class_id)
);

维护已经创建好的约束:

可添加或删除约束,但不能直接修改。
可使约束启用和禁用。
非空约束必须使用MODIFY子句增加。
为表增加主键约束:

--维护约束
--创建约束
create table tab_check(
 che_id number,
 che_name varchar2(20)
);
--为表增加主键约束
alter table tab_check
add constraints tab_check primary key(che_id);

--添加唯一约束,tab_check_unique表示约束的名称
alter table tab_check
add constraints tab_check_unique unique(che_name);

添加检查约束:

--添加一个字段
alter table tab_check
add che_age number;
--添加检查约束
alter table tab_check
add constraints tab_check_age check(che_age>18 and che_age<60);

--删除主键约束
alter table tab_check
drop constraints tab_check;

--禁用约束
alter table tab_check disable constraints tab_check;

--启用约束
alter table tab_check enable constraints tab_check;

复合约束,联合主键,也就是两个字段的组合成一个主键

--联合主键
create table tab_person(
 tab_firstname varchar2(10),
 tab_lastname varchar2(10),
 tab_gender varchar2(5),
 primary key(tab_firstname,tab_lastname)
);

为表添加外键约束:

alter table tab_stu
add constraints tab_stu foreign key(class_id) references tab_class(class_id);

相关阅读:

Oracle完整性约束 http://www.linuxidc.com/Linux/2013-04/82171.htm

Oracle的约束和索引 http://www.linuxidc.com/Linux/2012-12/76228.htm

从Oracle的约束到索引 http://www.linuxidc.com/Linux/2010-08/27544.htm

Oracle常用数据类型和完整性约束 http://www.linuxidc.com/Linux/2013-08/89449.htm

ORA-02291: 违反完整约束条件 …… - 未找到父项关键字 http://www.linuxidc.com/Linux/2013-08/89159.htm

更多Oracle相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12

linux
相关资讯       Oracle约束  Oracle创建约束 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款