Oracle 约束详解(constraint)

本文详细介绍了数据库中各种约束的作用,包括主键、外键、唯一、检查和非空约束。探讨了约束的命名规范、信息查询方法及如何添加、删除、重命名和禁用启用约束。通过实例展示了不同类型的约束创建方式。

1 概述

1. 约束的作用
   (1) 录入 '规范' 的数据
   (2) '定义规则',对数据库中数据进行限制,确保数据正确性、有效性、完整性

2 约束管理

2.1 约束命名规范

1. 默认命名:SYS_Cn(n 为正整数)
2. 指定名称:推荐如下
3. 若约束名称长度超过 30 个字节,则 "表名" 使用简称
约束类型规范命名名称说明
主键约束PK_表名_列名Primary Key
外键约束FK_表名_列名Foreign Key
非空约束NN_表名_列名Not Null
唯一约束UK_表名_列名Unique Key
检查约束CK_表名_列名Check

2.2 约束信息查询

1. 常用视图 (权限由大到小: dba_* > all_* > user_*)
   (1) dba_constraints : 侧重约束具体信息
   (2) dba_cons_columns: 侧重约束列信息

2. 参考如下
   select *
     from dba_constraints dc
    where dc.owner = 'SCOTT'
      and dc.table_name = 'EMP';
  
   select *
     from dba_cons_columns dcc
    where dcc.owner = 'SCOTT'
      and dcc.table_name = 'EMP';

2.3 添加约束

-- 1.唯一性约束
alter table 表名 add constraint uk_* unique(列名) [not null];

-- 2.检查约束
alter table 表名 add constraint ck_* check(列名 between 1 and 100); 
alter table 表名 add constraint ck_* check(列名 in ('值1', '值n')); 

-- 3.非空约束(多个约束中,not null 位于末尾)
alter table 表名 modify(列名 constraint nk_* not null);

2.4 删除约束

alter table 表名 drop constraint 约束名;

2.5 重命名约束

alter table 表名 rename constraint 约束名 to new_约束名;

2.6 禁用启用约束

-- 1.禁用 disable
alter table 表名 disable constraint 约束名 [cascade];

-- 2.启用 enable
alter table 表名 enable constraint 约束名 [cascade];

3 约束分类

3.1 主键约束 P

create table scott.sex (
   sex_code  varchar2(2) constraint pk_sex_code primary key,
   sex_desc  varchar2(10)
);

3.2 外键约束 R

create table scott.student_info (
   sno      number(10) constraint pk_student_info_sno primary key,
   sname    varchar2(30),
   sex_code varchar2(2),
   constraint fk_student_info_sex_code foreign key(sex_code) references scott.sex(sex_code)
);

外键约束有以下 3 种情况:子表 引用 父表

1. 普通外键约束: 删除 父表 记录时,'报错''默认'
2. 级联外键约束: 删除 父表 记录时,同时 '删除子表记录'
3. 置空外键约束: 删除 父表 记录时,同时将 '子表记录置为 null'

关系图如下:
在这里插入图片描述

3.3 唯一约束 U

create table scott.temp_u (
   tno number(10) constraint tk_temp_u_tno unique not null
);

3.4 检查约束 C

create table scott.temp_c (
   age number(3) constraint ck_temp_c_age check(age between 1 and 150),
   sex varchar2(2) constraint ck_temp_c_sex check(sex in ('男', '女', '未说明'))
);

3.4 非空约束

create table scott.temp_n (
   create_date date constraint nn_temp_n_create_date not null
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鱼丸丶粗面

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

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

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

打赏作者

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

抵扣说明:

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

余额充值