Oracle表约束的创建与管理

1. 主键约束

  • 创建表时建立主键约束
create table student(
    s_num varchar(10) constraint pk_stu primary key,    -- constraint用于指定约束名,可以省略
    ...
);
-- 或
create table student(
    s_num varchar(10),
    ...
    constraint pk_stu primary key(s_num)    -- constraint用于指定约束名,可以省略
);
  • 建立主键约束
alter table 表名 add [constraint 约束名] primary key(主键列名);

2. 外键约束

  • 创建表时建立外键约束
create table student(
    s_dept varchar(10),
    ...
    constraint fk_stu_dept foreign key(s_dept) references dept(dept_no) -- constraint用于指定约束名,可以省略
);
  • 建立外键约束
alter table 表名 add [constraint 约束名] foreign key(主键列名) references 主表名(主表主键);

3. 唯一约束

  • 创建表时建立唯一约束
create table student(
    s_name varchar(20) constraint uk_stu_name unique, -- constraint用于指定约束名,可以省略
    ...
);
-- 或
create table student(
    s_name varchar(20), -- constraint用于指定约束名,可以省略
    ...
    constraint uk_stu_name unique(s_name)
);
  • 建立唯一约束
alter table 表名 add [constraint 约束名] unique(列名)

4. 非空约束

  • 创建表时建立非空约束
create table student(
    s_name varchar(20) constraint nk_sname not null ,    -- constraint用于指定约束名,可以省略
    ...
);
  • 建立非空约束
alter table 表名 modify(
    s_name varchar(20) constraint nk_sname not null -- constraint用于指定约束名,可以省略
);

5. 检查约束

  • 创建表时建立检查约束
create table student(
    s_age number(2) constraint ck_stu_age check(s_age>0),-- constraint用于指定约束名,可以省略
    ...
);
-- 或
create table student(
    s_age number(2),
    ...
    constraint ck_stu_age check(s_age>0) -- constraint用于指定约束名,可以省略
);
  • 建立检查约束
alter table 表名 add [constraint 约束名] check(条件);

6. 默认值设置

  • 创建表时设置默认值
create table student(
        s_age number(20) default 18,   
    ...
);
  • 设置默认值
alter table 表名 modify(
    s_age number(20) default 18
);

7. 删除约束

alter table 表名 drop constraint 约束名;

8. 查询约束

  • 仅查询约束名
select * from user_constraints;
  • 查询约束名、作用列、所在表
select * from user_cons_columns;

9. 级联操作

  • 删除主表数据时,自动删除子表中对应的数据
建外键时后面加 on delete cascade;
  • 删除主表数据时,将子表的对应数据设置为null
建外键时后面加 on delete set null;
  • 删除主表时,解除其约束,强制删除
drop 表名 cascade constraint purge;

猜你喜欢

转载自www.cnblogs.com/rawlins/p/11895927.html
今日推荐