维护数据完整性

来源:互联网 发布:斗鱼刷人气软件购买 编辑:程序博客网 时间:2024/05/22 19:16

disable约束可以快速导入数据。

维护数据完整性方法
1.应用代码
2.数据库触发器
3.完整性约束

约束类型
1.NOT NULL
create table时设置表级constraint xxx not null,列级not null,
更改列级约束 alter table t modify id NOT NULL;

2.UNIQUE(会自动创建索引,如果该列或多列有索引,则使用已经定义的索引。)
可为NULL,null不等于null,
create table时设置表级unique,列级unique,
更改表级约束alter table t add constraint xxx unique(id,name);
或alter table t add  unique(id,name);数据库来命名约束名和索引名;

3.primary key
等于NOT NULL加上UNIQUE
create table时设置表级constraint xxx primary(id,name),列级id number(10) primary;

4.foreign key
更改表级约束alter table t add constraint xxx foreign key(partment_id) references department(id) on delete set null;
被引用的列要为主键或unique;

删除模式
delete no action(默认值):当删除父表中的记录时,对应的子表(被引用表)有记录时,不允许删除;
delete cascade(级联删除):删除父表记录对应的子表记录也响应相应删除;
delete set null:删除父表的记录,子表对应的改为null;

5.check(指定约束条件,是个布尔表达式)
create table时设置表级check,列级check,
更改表级约束 alter table t add constraint xxx check (id<10);


约束状态4种:
1.对将来要插入的数据:
disable:约束不立即生效;
alter table t add primary key(id) disable;
alter table t disable primary key;
enable:默认值,约束立即生效;
alter table t enable primary key;
2.对已经存在的数据:
novalidate:不校验
validate:校验
注:如果表中有不合法的唯一性约束记录时,不能从DISABLE状态变为enable状态;

步骤enable novalidate-》enable validate
alter table t enable novalidate constraint xxx|alter table t enable novalidate primary key
删除约束
alter table t drop constraint xxx(约束名);
alter table t drop unique(emp_id) cascade(有外键的情况加cascade)

延迟约束检查deferred(自动生成非唯一性索引)
立即检查
commit后检查:deferred
声明其属性为可延迟的 alter table t add primary key(id) deferrable;
使其生效     set constraints all deferred|set constraint xxx(约束名) deferred;
             或者alter session set constraints=deferred/immediate;

tip:如果子表的外键列没有索引的话,对父表进行更新时会使用共享锁把整个子表都锁定,降低了并发性。

把约束对应的索引放在不同的表空间上
create table t(
id number(7) constraint xxx primary key deferred
using index storage(initial 100k next 100k)  tablespace indx,//约束索引放indx表空间
name varchar(22))
tablespace users;

重命名约束
alter table t rename constraint xx to xxx;

查询不符合约束的信息
先执行@?rdbms/admin的utlexpt1.sql
在切换状态时alter table t ENABLE VALIDATE PRIMARY KEY EXCEPTIONS into exceptions;
查看不合法的行select rowid,id,name from t where rowid in (select row_id from exceptions);

约束数据字典
dba_constraints
dba_cons_columns

 

原创粉丝点击