从零开始学Oracle—约束(三)

继续上一篇:

                                                               给表添加约束
   主键约束 --  每个表要有主键,唯一的标识一行数据
   非空约束
   唯一性约束
   外键约束
   检查约束

查看一个表的约束:
      
select constraint_name,constraint_type
      from user_constraints
      where table_name = '表名'

查看约束作用于那个字段:
     select * from user_cons_columns
     where CONSTRAINT_NAME='约束名;

  1.建立表的同时使用约束
        create table student( --学生表
           xh number(4) primary key, --学号主键
           xm varchar2(10) not null, --姓名不能为空
           sex char(2)  check (sex in ('男','女')), --性别
           birthday date unique, --日期
           sal number(7,2) check (sal between 500 and 1000),--奖学金 sal >=500 and sal <=1000
           classid number(2) references cla(id)
        );  --必须要先有cla表才对
            --一定先建立班级cla表
 2.建立约束的同时给约束指定名字,便于删除
        
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),
          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 student add constraint fk_stu  foreign key (classid) references cla(id);
添加唯一约束:  alter table student add constraint  uq_sfz unique(shenfenzheng);
4.删除约束:
  格式:alter table 表名 drop constraint 约束名

     alter table student drop constraint  fk_stu;

原文地址:https://www.cnblogs.com/sunjie9606/p/2167406.html