日期:2014-05-16  浏览次数:20466 次

oracle学习笔记11--约束
维护数据的完整性
约束
约束用于确保数据库数据满足特定的商业规则。在oracle中,约束包括:not null,unique,primary key,foreign key,check五种。
not null:不能在定义了not null的列插入空值
unique:该列值 不能重复,但是可以为null
primary key:not null和unique的组合,就是说定义为主键的列既不能为空,也不能重复。一张表只能有一个主键,可以是一列,也可以是多列的组合,但是必须可以唯一标示一个元组。
foreign key:用于定义主表和从表之间的关系。外键约束要定义在从表上。主表则必须具有主键约束或是unique约束,当定义外键约束后,要求外键列数据必须在主表的主键列存在或是为null。
check:用于强制行数据必须满足的条件,假定在sal列上定义了check约束,并要求sal列值在1000~2000之间,如果不在1000~2000之间就会提示出错。
举个例子:
create table purchase(customerId char(8) references customer(customerId), goodsId char(8) references goods(goodsId),nums number(3) check(nums between 1 and 30));
上面定义的三个约束都是列级约束,因为都是在每个字段定义结束之后立刻给出了约束;我们也可以使用表级约束,就是在把所有字段都给出之后再给出约束条件。举个简单的例子:
create table employee2(
emp_id number(4),
name varchar2(25),
dept_id number(2),--所有字段定义结束,接下来定义约束
constraint pk_employee primary key(emp_id),
constraint fk_department foreign key(dept_id)
references department(dept_id));
注意:not null只能在列级上定义
如果认为不合适,可以对约束作出修改:
alter table goods modify goodsName not null;
alter table customer add constraint cardunique unique(cardId);
alter table customer add constraint addrcheck check(address in ('东城','西城'));
constraint是关键字,其后跟的是约束名,这个约束名也很有用,如果你不想要某个约束了,那么你就可以通过这个约束名来删除这个约束:
alter table 表名 drop constraint 约束名;
注意alter table 表名 drop primary key;可能会出问题,因为如果已经存在了主从关系,那么当你删除了主键后,从键就没法办了,所有数据库会提示错误信息,让你级联删除:
alter table 表名 drop primary key cascade;
显示约束信息:
1. 通过查询数据字典视图user_constraints,可以显示当前用户的所有的约束信息。
select constraint_name,constraint_type,status,validated from user_constraints where table_name=’表名’;
2. 显示约束列
通过查询数据字典视图user_cons_columns,可以显示约束所对应的表列信息:
select column_name,position from user_cons_columns where constraint_name=’约束名’;
3. 可以通过PL/SQL DEVELOPER 直接查看~~~