达梦数据库的约束常用的有主键约束, 外键约束, 唯一约束, 还有些不常用的检查约束, 非空约束等等, 接下来我们使用 test1 用户分别来创建操作下.
1, 创建主键约束
我们先来用 test1 用户创建一个 tab1 表来测试, 同时创建 id
create table tab1 (id int primary key, name char);
插入一条数据正常
insert into tab1 values(2, 'a');
再次插入就会提示插入失败, 提示违反表 [TAB1] 唯一性约束.
insert into tab1 values(2, 'b');
2, 创建外键约束
- create table tab2(id int unique, name char);
- create table tab3 (id int references tab2(id),name date );
向两个表中插入数据正常
insert into tab2 values (1, 'a'); insert into tab2 values (2, 'b'); insert into tab3 values (1,'2019-11-28'); insert into tab3 values (2,'2019-11-28');
再次插入就会提示插入失败, 提示违反引用约束[CONS134218851].
insert into tab3 values (3,'2019-11-28');
3, 创建唯一约束
create table tab4 (id int unique, name char);
插入数据正常
insert into tab4 values (1, 'a');
再次插入就会提示插入失败, 违反表 [tab4] 唯一性约束.
insert into tab4 values (1, 'b');
4, 创建表后再添加或删除约束
创建表后再添加约束
create table tab5 (id int, name char(10)); alter table tab5 add constraint con_id primary key(id);
删除约束
alter table tab5 drop constraint con_id;
来源: http://www.bubuko.com/infodetail-3307913.html