Oracle数据库中怎么创建字段约束

发布时间:2021-06-23 17:19:27 作者:Leah
来源:亿速云 阅读:345

本篇文章给大家分享的是有关Oracle数据库中怎么创建字段约束,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

  1. 非空约束

  2. 唯一约束

  3. 对字段的取值的约束

  4. 默认值

  5. 外键约束

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)  
);

维护已经创建好的约束:

  1. 可添加或删除约束,但不能直接修改。

  2. 可使约束启用和禁用。

  3. 非空约束必须使用MODIFY子句增加。

  4. 为表增加主键约束:

--维护约束 
--创建约束 
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数据库中怎么创建字段约束,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么样约束MySQL字段
  2. 查询oracle表的信息(表,字段,约束,索引)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

oracle

上一篇:Python中怎么利用递归算法实现汉诺塔

下一篇:微信小程序中怎么利用三元运算验证手机号

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》