---
title: "建表并修改表约束"
author: "jonsamwang"
date: "2010-01-08T15:00:37Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2010-01-08T15:00:37Z"
id: 565852
url: "https://jonsam.iteye.com/blog/565852"
---

主键约束 primary key  
           not null  
           check  
           unique 唯一约束          

 create table student( --学生表  
           xh number(4) constraint pk\_stu primary key, --学号主键  
           xm varchar2(10) constraint nn\_stu not null, --姓名不能为空  
           sex char(2) constraint ck\_stu\_sex check (sex in ('男','女')), --性别  
           birthday date constraint uq\_bir unique, --日期  
           sal number(7,2) constraint ck\_sal check (sal between 500 and 1000)--奖学金 sal &gt;=500 and sal &lt;=1000  
        );  
      &lt;2&gt;建立约束的同时给约束指定名字，便于删除  
        create table cla( --班级表  
          id number(2) constraint pk\_cla primary key, --班级编号  
          cname varchar2(20) constraint nn\_cla not null --班级名字  
       );  
       
      create table stu( --学生表  
          xh number(4) constraint pk\_stu primary key, --学号是主键  
          xm varchar2(20) constraint nn\_stu not null, --姓名非空  
          age number(2) constraint ck\_stu check (age between 10 and 90),--年龄在10到90之间(10&lt;= age  &lt;=90 )  
          birthday date,  
          shenfenzheng number(18) constraint uq\_stu unique, --身份证唯一   
          classid number(2) constraint fk\_stu references cla(id) -- 班级编号外键  
           --(引用的一定是另外表的主键或唯一性约束的字段)  
         );  
3）建完表后加约束  
加约束  
   加主键  
    alter table student add constraint pk\_stu  
    primary key (xh);  
   加非空  
    alter table student modify (xm not null);  
   检查约束  
    alter table student add check(sex in ('男','女'));  
    alter table student add constraint ck\_sal check(sal between 500 and 1000));  
添加 主键  
 alter table cla add constraint pk\_cla  
       primary key (id);  
加 not null  
 alter table cla modify  
       (cname not null);

学生表student:

      create table student(  
          xh number(4) ,  
          xm varchar2(20) ,  
          age number(2),  
          birthday date,  
          shenfenzheng number(18),  
          classid number(2)  references cla(id)         
         );

加外键约束  
alter table student add constraint fk\_stu  
    foreign key (classid) references cla(id);

加主键  
alter table student add constraint pk\_stu  
 primary key (xh);

加not null  
alter table student modify(xm not null);

加检查约束  
alter table student add constraint cc\_age  
 check (age &gt;= 10 and age &lt;=90);

加唯一约束  
  alter table student add constraint  
      uq\_sfz unique(shenfenzheng);

加外键约束  
 alter table student add constraint  
    fk\_stu foreign key (classid)  
     references cla(id);