达梦数据库的约束操作

达梦数据库的约束操作

达梦数据库的约束常用的有主键约束、外键约束、唯一约束,还有些不常用的检查约束、非空约束等等,接下来我们使用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;
达梦数据库的约束操作

猜你喜欢

转载自blog.51cto.com/14615334/2454622