oracle 主键,非空,检查,唯一,默认,外键约束

--首先添加主键约束
alter table student
add constraint PK_student_sno primary key(sno)

--删除约束
alter table student
drop constraint PK_student_sno

--not null
alter table student
modify (sname varchar2(30) not null)

--check 检查约束
alter table student
add constraint CK_student_sex check(sex = '男' or sex = '女')

--默认约束
alter table student
modify (address varchar2(20) default '湖南软件评测中心')

--唯一约束
alter table student
add constraint UQ_student_cardid unique(cardid)


--外键约束
alter table score
add constraint FK_student_score foreign key(sno) references student(sno)

或者

--方式一:直接将约束写在字段的后面
create table student
(
sno int primary key,--主键
sname varchar2(20) not null,--非空
sex varchar2(2) check(sex in ('男','女')),--check(sex ='男'or sex='女'),
address varchar2(20) default '湖南长沙',--默认约束
cardid varchar2(20) unique not null --唯一
)


--方式二:将所有字段写好后在来写约束
create table test
(
sno int ,
sname varchar2(20),
constraint PK_TEST primary key(sno)
)

-- 外键约束
--(oracle里面创建表的同时创建外键约束的时候如果是将约束直接写在单个的字段后面是不需要加foreign key)
--(oracle里面创建表的同时创建外键约束的时候如果是将约束直接写在所有的字段后面是需要加foreign key)
create table score
(
sno int references student(sno),
cno int,
grade float,
constraint PK_score primary key(sno,cno),
constraint FK_STUDENT_SCORE foreign key(cno) references course(cno)
)

扫描二维码关注公众号,回复: 2679601 查看本文章

猜你喜欢

转载自www.cnblogs.com/wangxuekui/p/9457507.html