关于oracle数据库(6)约束

约束类型

1、主键primary key(一般是一个表的标志,所以一个表只能有一个主键;主键不能为空,不能重复)

2、唯一键unique(不能重复)

3、外键foreign key

4、检查约束check(not null不能为空;default默认值)

建表的同时添加约束

create table person(

  pid number(18) primary key,              --primary key主键,不能为空,不能重复

  name varchar2(50) unique not null,           --unique唯一约束,不能重复,可以为空;not null不能为空

  sex varchar2(4) default '男' check(sex in('男','女')),    --性别必须是男或女,default默认为男

  age number(3) check(age>0 and age<=120)       --年龄数据类型为3位,check里条件规定了范围

)

后期添加(约束表已经建立好不能删除)

添加约束

  修改表  表名  添加  约束  起名字  约束类型  列名

  alter table 表名 add constraint 起名字 约束类型  (列名);

添加主键

alter table 表名 add constraint 起名字 primary key (列名);

如:alter table student add constraint pk_sid primary key (sid);

添加唯一约束

alter table 表名 add constraint 起名字 unique (列名);

如:alter table student add constraint uq_name unique (name);

添加检查约束

alter table 表名 add constraint 起名字 check(条件);

如:alter table student add constraint ck_sex check(sex in('男','女'));

添加默认值(modify修改)

alter table 表名 modify 列名 default '女';

如:alter table student modify sex default '女';

修改表的字段类型(modify修改)

alter  table 表名 modify 列名 数据类型; 

如:alter  table student modify sex varchar2(5); 

如:alter table student modify name not null;

修改表结构

alter table 表名

modify 列名 数据类型

modify 列名 default 'something'

如:alter table studentinfo

  modify stuname varchar(20)

  modify stusex default '男'

建表时添加外键

如:create table student(

    cid number(12) references myclass  --myclass是另一个表名

  )

后期添加外键约束

alter table 表名 add constraint 起名字 foreign key (列名) references 表名;

如:alter table student add constraint fk_cid foreign key (cid) references myclass

删除约束

alter table 表名 drop constraint 约束名称

找约束名称

 select * from user_constraints where table_name='表名'

如:select * from user_constraints where table_name='student'

回滚(oracle数据库 默认添加的数据是需要提交的 ,不提交其它的人看不到)

(刚添加修改删除的数据没有保存到数据库,只是临时的)

commit;         --提交 永久的的保存到数据库了

rollback table 表名 ;  --回退没提交之前的数据

truncate table  表名;  --表截断,立刻清除表里面的所有数据并且不能回滚

SQL结构化查询语言

1、DDL数据定义语言  不能回滚

  create,alter,drop

2、DML数据操作语言  可以回滚

  insert,delete,update,select

3、DCL数据控制语言  权限

  grant,revoke

4、TCL事务控制语言

  commit,rollback

数据移植:导入导出.dmp,在cmd中执行命令

原文地址:https://www.cnblogs.com/xsl1995/p/5307354.html