Oracle数据库约束(constraint)

 最近一张表上有两列字段,要求这两列要么都有值,要么都为空,简单的table定义没办法实现这种要求,需要利用Oracle的constraint(约束)机制。约束主要是用来保证数据的完整性。

  可以从TOAD的设置上,很容易看到约束分为4种,分别是主键(Primary Key),检查(Check),唯一性(Unique),外键(Foreign Key)。另外还有两种是NOT NULL和REF,REF就是其中的一列或者几列是另外一张表中的值。

  下面是对着6中的详细介绍。

  * NOT NULL constraint prohibits a database value from being null.

  * Unique constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.

  * Primary Key constraint combines a NOT NULL constraint and a unique constraint in a single declaration. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null.

  * Foreign Key constraint requires values in one table to match values in another table.

  * Check constraint requires a value in the database to comply with a specified condition.

  * REF column by definition references an object in another object type or in a relational table. A REF constraint lets you further describe the relationship between the REF column and the object it references.

对于我们的要求,符合的是Check,可以通过增加一个条件是( A is null and B is null ) or ( A is not null and B is not null) 的约束来实现。

  对于约束,主要的状态有两种,一个是Status on Creation,也就是在表中增加数据或修改数据时是否使用约束,可选值是Enabled和Disabled;另外一种是Validation,它表示是否对表中现有的数据是否进行验证,可选值是Validate和NoValidate。

对于上面这两种状态,有4种组合,下面是对着四种的详细介绍。

  * ENABLE VALIDATE is the same as ENABLE. The constraint is checked and is guaranteed to hold for all rows.

  * ENABLE NOVALIDATE means that the constraint is checked, but it does not have to be true for all rows. This allows existing rows to violate the constraint, while ensuring that all new or modified rows are valid.

  In an ALTER TABLE statement, ENABLE NOVALIDATE resumes constraint checking on disabled constraints without first validating all data in the table.

  * DISABLE NOVALIDATE is the same as DISABLE. The constraint is not checked and is not necessarily true.

  * DISABLE VALIDATE disables the constraint, drops the index on the constraint, and disallows any modification of the constrained columns.

  约束的设置还有一个延迟性设置,默认是非延迟的,也就是Initially Immediate,这种情况下任何的修改都会进行校验,另外一种是延迟的,也就是Intially Deferred,会在所有修改完成后commit的时候校验,进而引发回滚。

来源:http://www.examda.com/oracle/zonghe/20110104/114218697.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值