oracle 定义数据完整性

本文详细介绍了SQL中的五种主要约束:主键、非空、唯一、检查和外键约束。包括如何在创建表时及创建表后添加这些约束,以及如何通过ALTER TABLE命令进行约束的修改和删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 定义主键约束

1.1 在创建表时定义主键约束

create table student
(
name varchar2(8),
studentid varchar2(10) primary key,
sex char(2)
);

1.2 创建表后,使用alter table命令添加约束

1.2.1 创建表

create table student
(
name varchar2(8),
studentid varchar2(10),
sex char(2)
);

1.2.2 添加主键约束

alter table student
add constraint pk_student primary key(studentid);

其中 constraint pk_student 用于给该主键约束定义名称(可省略)

其中 pk_student   为约束名,用于修改约束,

例如:删除该主键约束

alter table student

drop constraint pk_student  ;

2 定义not null约束

not null 约束只能定义为列级约束

2.1 在创建表时定义not null约束

同样的not null约束可以在创建表时定义

eg:

create table tset
(
name varchar2(8) NOT NULL,
studentid varchar2(10) primary key,
sex char(2)
);

2.2 创建表后,在修改表添加not null约束

2.2.1 创建表

create table tset
(
name varchar2(8),
studentid varchar2(10) primary key,
sex char(2)
);

2.2.2添加not null约束

alter table test modify name not null;

3 定义唯一性 unique约束

唯一性约束是指:被约束的字段不能出现重复输入的值

唯一性与逐渐的区别:

(1)unique一个表可以定义多个,而primary key 一个表只能定义一个

(2)unique允许被约束的字段为空,而primary key不允许为空

3.1 创建表示定义unique约束

create table test
(
name varchar2(8) NOT NULL,
studentid varchar2(10) primary key,
sex char(2),
idnum char(18) unique
);

3.2创建表后,为表添加unique约束

3.2.1 创建表

create table test
(
name varchar2(8) NOT NULL,
studentid varchar2(10) primary key,
sex char(2),
idnum char(18)
);

3.2.2 添加约束

alter table test

add constraint un_idnum unique(idnum);

 

4 定义检查check约束

检查约束用来指定某列的可取值得范围,只有符合条件的值才能输入到表中

4.1 在创建表时定义check

create table test
(
name varchar2(8) NOT NULL,
studentid varchar2(10) primary key,
sex char(2) constraint ch_sex check(sex in ('男','女')),
idnum char(18)
);

4.2.1 创建表

create table test
(
name varchar2(8) NOT NULL,
studentid varchar2(10) primary key,
sex char(2),
idnum char(18)
);

4.2.2 添加检查约束

alter table test add constraint ch_sex

check(sex in('男','女'));

5 定义外键约束

5.1 创建表示定义外键

5.1.1 在定义字段时定义外键

 

create table course
(
id varchar2(10) primary key,
classname varchar2(10),
studentid VARCHAR2(10) references test(studentid)
)

5.1.2  定义字段后,再定义外键

create table course
(
id varchar2(10) primary key,
classname varchar2(10),
studentid VARCHAR2(10),
constraint fk_course foreign key(studentid) references test(studentid)
);

*************注意两种方式的区别*****************

5.2 通过alter table 命令创建外键约束

alter table course

add constraint fk_course foreign key(studentid) references test(studentid);

 

 

 

 

转载于:https://www.cnblogs.com/pretty-guy/p/3227686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值