【Oracle学习】之 外键约束(3种删除-详细)与 约束激活(失效)
发布时间:2020-12-12 15:01:47 所属栏目:百科 来源:网络整理
导读:Q:删除主表记录(子表外键存在下),3种删除方式? A:①默认删除(default) ②级联删除 ③置空删除。具体操作见下文 主表和子表的概念: 如果表中定义了外键约束,那么该表通常被称为 子表 ,例如下文的test_student表 如果表中包含引用键,那么该表被称
一、外键删除①默认删除—-即什么都不加 或 使用 no action关键字简介:如果在定义外键约束时使用no action关键字,那么当父表中被引用列的数据被删除时,将违反外键约束,改操作也将被禁止执行,这也是外键约束的默认引用类型。//查看test_student 有哪些约束
select constraint_type,table_name from user_constraints where table_name = 'TEST_STUDENT';
//添加约束
alter table test_student add constraint FK_TAB_STUDNET_TAB_CLASS foreign key (s_fk_id) references test_class (c_id);
select * from test_class;
select * from test_student;
delete from test_class where c_id = 1;
②级联删除—-使用关键字 cascade简介:如果在定义外键约束时使用cascade关键字,那么当父表中被引用列的数据被删除时,子表中对应的数据也将被删除。//删除
alter table test_student drop constraint FK_TAB_STUDNET_TAB_CLASS;
//添加
alter table test_student add constraint FK_TAB_STUDNET_TAB_CLASS foreign key (s_fk_id) references test_class (c_id) on delete cascade;
select * from test_class;
select * from test_student;
delete from test_class where c_id = 1;
③置空删除—-使用关键字set null简介:如果在定义外键约束时使用set null关键字,那么当主表中被引用列的数据被删除时,子表中对应的数据被设置为null。要使这个关键字起作用,子表中的对应列必须支持NULL值。//删除
alter table test_student drop constraint FK_TAB_STUDNET_TAB_CLASS;
//添加
alter table test_student add constraint FK_TAB_STUDNET_TAB_CLASS foreign key (s_fk_id) references test_class (c_id) on delete set null;
select * from test_class;
select * from test_student;
delete from test_class where c_id = 1;
二、禁止和激活约束①禁止状态(DISABLE):当约束处于禁止状态时,即使对表的操作与约束规则相冲突,操作也会被执行。//使失效
alter table test_student disable constraint FK_TAB_STUDNET_TAB_CLASS;
//查看状态
select constraint_type,table_name,status from user_constraints where table_name = 'TEST_STUDENT';
select * from test_class;
select * from test_student;
delete from test_class where c_id = 1;
insert into test_student (s_id,s_name,s_fk_id) values (3,'TITI',3);
②激活状态(ENABLE):当约束处于激活状态时,如果对表的操作与约束规则相冲突,则操作会被取消。//使有效
alter table test_student enable constraint FK_TAB_STUDNET_TAB_CLASS;
//查看状态
select constraint_type,3);
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |