Oracle创建约束


数据库表创建成功后,通常都需要向表中添加约束,常用的约束级创建方式如下:

创建约束

1、主键约束
添加主键约束的表的字段必须有唯一值,而且必须为空。
alter table test add primary key(id)

2、外键约束
表中的一个非主键字段和另一张表的主键子段取值相关联。
创建外键约束:
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id)
可以给外键约束加上 on delete cascade,表示在父表中删除数据时子表对应的数据也被删除。
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id) on delete cascade;
如果加上 on delete set null 则表示父表中删除数据时与子表的数据置空。
alter table test add constraint foreignTest foreign key(audit_id) refrences audit_test(id) on delete set null;
如果加上 novalidate关键字,则表示已经存在的数据不受外键约束,新增加的数据会受外键约束。
alter table test add novalidate constraint foreign key(audit_id) refrences audit_test(id)
3、Check约束
Check约束会检查数据是否符合特定的规则。
alter table test add constraint checkTest check(color in (‘red’,‘yellow’,‘blue’))

4、非空约束
非空约束检查字段不能为空,同时非空约束必须用modify
alter table test modify name constraint nullTest not null

5、唯一约束
唯一约束是字段中的值必须是唯一的,字段可以为空
alter table test add constraint uniqueTest unique(male)

启用约束和禁用约束

禁用约束 创建好约束默认是启用状态,如果要禁用约束,可以在末尾加上disabled 禁用约束 alter table test add primary key(id) disable 或者 alter table test disable constraint uniqueTest 如果在禁用约束末尾加上cascade,则可以禁用依赖于指定约束的所有约束 alter table test disable constraint testid11 cascade 启用约束 alter table test enable constraint testid_primary

删除约束

drop constraint testid_primary
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael X LI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值