oracle约束详解

--约束学习:
--主键约束
--列级约束:在字段后面直接添加 :primary key
--表级约束:在创建表的后面使用:constraints 说明 primary key(字段名)
--非空约束
--在字段后面添加:not null
--检查约束
--在字段后面使用:default 默认值 check(条件),允许有空值。没有值则给默认值
--在创建表的后面使用:constraints 说明 check(条件)
--唯一约束
--在字段后面添加:unique ,允许有多个空值
--在创建表的时候:constraints uk_student_mail unique(mail)
--除了非空,还可以在创建表后使用alter添加
--alter table student add constraints 说明 primary key(字段名)
--alter table student add constraints 说明 check(条件)
--alter table student add constraints 说明 unique(字段)
--alter table student drop constraints 说明
-----使用外键:
--在字段后面使用:references 表名(参照表字段)
--在创建表的时候使用:constraints 说明 foreign key(本表字段) references 参照表(参照表字段)
--在创建表后添加: alter table student add constraints 说明 foreign key(本表字段名) references 参照表(参照表字段);
下面是具体事例详解
1:域完整性约束(非空和检查约束 not null和check)
非空约束
(1):create table stu(
id number ,
name varchar(20) not null
)
(2):alter table stu modify name varchar(20) not null;
ckeck检查约束
(1) create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) default '男' check (sex='男' or sex='女')
)
(2):create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) ,
constraints ck_stu_sex check (sex='男' or sex='女')
)
(3):alter table stu add constraints ck_stu_sex check(sex='男' or sex='女')
alter table stu drop ck_stu_sex
2:实体完整性约束(唯一unique,主键约束primary key)
(1):主键约束
第一种方式 (字段名后面跟约束)
create table stu(
id number(10) primary key;
name varchar(20)
第二种方式 (在表字段声明完毕处用contraints关键字)
create table stu(
id number,
name varchar(20)
constraints pk_stu_id primary key(id) --pk_stu_id 约束名 可以随便起 这里是规范
第三种 方式 (在表创建完成后使用alter关键字修改)
alter table stu add constraints pk_stu_id primary key(id);
alter table stu drop constraints 约束名(即 pk_stu_id);
(2):唯一约束
(1) create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) default '男' check (sex='男' or sex='女')
)
(2):create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) ,
constraints uk_stu_name unique(name)
)
(3):alter table stu add constraints uk_stu_name unique(name)

3:参照完整性约束(外间约束foreign key)
(1) create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) ,
cid number(2) references clazz(clazzid)
)
(2) create table stu(
id number ,
name varchar(20) not null,
sex varchar(2) ,
cid number(2),
constraints fk_stu_cid foreign key(cid) references clazz(clazzid) on delete set null
)
(3)alter table stu add constraints fk_stu_cid foreign key(cid) references clazz(clazzid) on delete set null (被置为空)
alter table stu add constraints fk_stu_cid foreign key(cid) references clazz(clazzid) on delete cascade(级联删除)


命名规则推荐采用:约束类型_约束字段
非空约束     NN__表名列名
唯一约束     UK_表名_列名
主键约束     PK_表名
外键约束     FK_表名_列名
检查约束     CK_表名_列名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值