---
title: "如何在Oracle中建表格时就指定主键和外键"
author: "java1573"
date: "2007-11-29T23:31:56Z"
tags: []
slug: "oracle"
draft: false
lastmod: "2007-11-29T23:31:56Z"
id: 144959
url: "https://java1573.iteye.com/blog/144959"
---

创建表的语法  
\-创建表格语法:  
create table 表名(  
   字段名1  字段类型(长度) 是否为空,  
   字段名2  字段类型       是否为空  
);

-增加主键  
alter table 表名 add constraint 主键名 primary key (字段名1);

-增加外键:  
alter table 表名  
   add constraint 外键名 foreign key (字段名1)  
      references 关联表 (字段名2);

在建立表格时就指定主键和外键

create table T\_STU  (  
   STU\_ID               char(5)                         not null,  
   STU\_NAME             varchar2(8)                     not null,  
   constraint PK\_T\_STU primary key (STU\_ID)  
);

主键和外键一起建立：  
create table T\_SCORE  (  
   EXAM\_SCORE           number(5,2),  
   EXAM\_DATE            date,  
   AUTOID               number(10)                      not null,  
   STU\_ID               char(5),  
   SUB\_ID               char(3),  
   constraint PK\_T\_SCORE primary key (AUTOID),  
   constraint FK\_T\_SCORE\_REFE foreign key (STU\_ID)  
      references T\_STU (STU\_ID)  
)