---
title: "Oracle中的约束条件"
author: "slbszq"
date: "2014-01-17T10:20:20Z"
tags: ["Oracle", "约束"]
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2014-01-17T10:20:20Z"
id: 2005541
url: "https://it4j.iteye.com/blog/2005541"
---

**Oracle中的约束条件**

 

1.**主键约束**（**primary key** \[pk]）**不能重复，不能为****null**。

添加代码：**constraint** constraint\_name **primary key** (**column**)

 

2.**外键约束**（**foreign key** \[fk]）**可以为****null。**

**constraint** constraint\_name **foreign key** (**column**) **references** table\_name(**column**);

 

3.设置**唯一约束**（**unique** \[uk]）不能重复的，但是**可以为****null**。

创建表时，最后添加如下代码：

**constraint** constraint\_name **unique** (**column**)

 

4.**非空约束**（**not null** \[nn]） **只能定义在列级定义，定义表后添加使用modify关键字**。

 

5.**核查约束**（**check** \[ck]）

**constraint** constraint\_name **check**(**condition**)

 

6.**查询核查约束**

select **constraint\_name**,**constraint\_type**,**search\_condition**

from **user\_constraints** where table\_name='emp';

 

7.**增加约束条件**(**其中not null必须使用modify,不能使用add**)

**alter** **table** tablename **add** \[**constraint** constraintname] type (**column**)

eg:alter table depart

add constraint depart\_empid\_fk

foreign key(empid) **references** emp(empid);

 

8.**启动，关闭**约束条件

启动：alter table depart

**enable** **constraint** depart\_empid\_fk;

 

关闭：alter table depart

**disable** **constraint** depart\_empid\_fk;

 

9.**删除**约束条件

alter table depart

**drop** **constraint** depart\_empid\_fk;

10.**重建**约束条件（以主外键为例）

       alter table student\_yin add

           **constraint** stu\_y\_mid\_fkey **foreign key**(mid) **references** mid\_yin(mid\_no)

           **on delete set null**;

           --当**删除主表（****mid\_yin）的记录时** **子表中依赖该记录的记录被置空**

      

       alter table student\_yin add

           constraint stu\_y\_mid\_fkey foreign key(mid) references mid\_yin(mid\_no)

           **on delete cascade**;

 

           --**当删除主表（mid\_yin）的记录时** **子表中依赖该记录的记录被同时删除**

11.**表级**约束和**列级**约束

**列级定义**是**在定义列的同时定义约束**。

**表级定义**是指**在定义了所有列后，再定义约束**。

注意： **not null****约束只能在列级上定义。**