您的位置:首页 > 数据库 > Oracle

oracle中的约束操作

2017-08-05 16:36 232 查看
在数据库中的五中约束

1、primary key:主键约束

2、foreign key:外键约束

3、check :自定义的检查约束

4、not null:不为空的约束

5、unique: 唯一约束

创建一个没有外键关联的表

create table lyd(

id number(10) constraint id primary key,

name char(12) not null,

age number(3) check(age>0 and age<150)

);

select * from lyd;

在表里面插入字段

insert into lyd values(201701,'java',18);

insert into lyd values(201702,'pyhon',18);

insert into lyd values(201703,'c#',18);

commit;

列级约束:在列声明的后面设置约束

五种约束条件都可以在列级定义

表级约束除了not null,其它都可以

select * from emp;

create table 表名(列,列,、)

create table yd(

id number(10) constraint empno primary key,

name char(10) not null,

age  number(3) check(age>0 and age<150),

tid number(8),

constraint emp_fk

foreign key(tid)

references emp(id)

)

select * from yd;

constraint:约束名,约束条件,可有可无

create table ydd(

lid number(10) constraint hhh primary key,

name char(10) not null,

age  number(3) check(age>0 and age<150),

tid number(8),

constraint lyd_fk

foreign key(tid)

references lyd(id)

)

select * from ydd

建立的关键之后,一张表的外键,作为另一张表的主键,必须在在外键中包含另一张表主键的字段;

insert into ydd values(1200,'java',18,201701);

insert into ydd values(1201,'haha',18,201702);

insert into ydd values(1202,'guagau',18,201703);

commit;

更新

update 表名 set 列=value,...[where]

update ydd set lid=1200,name='php',age=18,tid=201701 where lid=1200;

dml:数据操作语句

update ydd set name='kkk' where lid=1200;

commit;

alter:修改

添加列

alter table 

表名 add 列 数据类型(size)

此处最好不要加not null约束条件

alter table 

ydd add sex char(6)

check(sex='男' and sex='女');

默认的使用

alter table 

ydd add address varchar2(40)

default '**省**市**大道';

删除表

alter table 表名 drop column 列名

alter table ydd drop column sex;

修改列

alter table 表名 modify 列 数据类型()

alter table ydd modify name varchar(12);

select length(name) from ydd

where lid=1200;

修改表名

alter table 表名

rename column 旧列 to 新列

alter table ydd 

rename column lid to id;

清空表

ddl:数据定义语言,不能进行回滚

dml:数据操纵语言,能进行回滚;

drop:清空表,表结构都没有 ddl不能回滚

delete : 清空表,可以删除指定的数据,表结构还在, dml可以回滚;

truncate:清空表,可以删除指定的数据,表的结构还在,ddl不能回滚

添加约束条件

create table tea(id number(12),

name char(16));

alter table tea 

add tid number;

alter table ydd

add yid number;

alter table 表名

add constraint 约束(列)(此时只是一个别名)

约束

添加主键约束

alter table tea

add constraint id_pk

primary key(id);

添加外键约束

在外键约束中,A表的外键作为B表的主键

alter table tea

add constraint t_fk

foreign key(tid)

references ydd(id)

删除约束

alter table 表名

drop constraint 约束名

alter table tea

drop constraint t_fk;

约束失效

alter table 表名

disable constraint 约束名

alter table tea

disable constraint id_pk

约束生效

alter table tea

enable constraint 约束名

alter table tea

enable constraint id_pk

 

删除表

drop table 表名

清空表

truncate table 表名

速度上面的比较

drop > truncate>delete
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  约束