---
title: "oracle建表、建主键、外键基本语法"
author: "sdk4986"
date: "2013-11-04T14:42:40Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2013-11-04T14:42:40Z"
id: 1969702
url: "https://sdk4986.iteye.com/blog/1969702"
---

**-创建表格语法:**  
     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)  
)