
--
创建测试主表.
ID
是主键.
CREATE
TABLE
test_main
(
id
INT
NOT
NULL,
value
VARCHAR(10),
PRIMARY
KEY(id)
)
--
创建测试子表.
CREATE
TABLE
test_sub
(
id
INT
NOT
NULL,
main_id
INT
,
value
VARCHAR(10),
PRIMARY
KEY(id)
)
--
插入测试主表数据.
INSERT
INTO
test_main(id,
value)
VALUES
(1,
'ONE')
INSERT
INTO
test_main(id,
value)
VALUES
(2,
'TWO')
--
插入测试子表数据.
INSERT
INTO
test_sub(id,
main_id,
value)
VALUES
(1,
1,
'ONEONE')
INSERT
INTO
test_sub(id,
main_id,
value)
VALUES
(2,
2,
'TWOTWO')
然后,创建外键,使用
ON
DELETE
CASCADE
选项,删除主表的时候,同时删除子表
ALTER
TABLE
test_sub
ADD
CONSTRAINT
main_id_cons
FOREIGN
KEY
(main_id)
REFERENCES
test_main
ON
DELETE
CASCADE
执行删除:
DELETE
FROM
TEST_MAIN
WHERE
ID
=
1
最后:
SELECT
*
FROM
TEST_MAIN
结果子表中就只有ID=2的记录,也就说明级联删除成功。
级联删除你可以把它认为是一个触发器,也就是你删除主表中的数据,那么从表中的相关联的也就一起删除了。。。看个例子:======================create table a\x0d\x0a(\x0d\x0aid varchar(20) primary key,\x0d\x0apassword varchar(20) not null\x0d\x0a)\x0d\x0a\x0d\x0acreate table b\x0d\x0a(\x0d\x0aid int identity(1,1) primary key,\x0d\x0aname varchar(50) not null,\x0d\x0auserId varchar(20),\x0d\x0aforeign key (userId) references a(id) on delete cascade\x0d\x0a)\x0d\x0a表B创建了外码userId 对应A的主码ID,声明了级联删除\x0d\x0a测试数据:\x0d\x0ainsert a values ('11','aaa')\x0d\x0ainsert a values('23','aaa')\x0d\x0ainsert b values('da','11')\x0d\x0ainsert b values('das','11')\x0d\x0ainsert b values('ww','23')\x0d\x0a删除A表内id为‘11’的数据,发现B表内userId 为“11”也被数据库自动删除了,这就是级联删除\x0d\x0adelete a where id='11'=============================================================级联更新也大同小异。。只是关键字为:on update希望回答对你有所帮助........两种方法,个人建议你选择方法一,简单方便方法一:触发器解决(下面的代码可以不用修改,copy直接用)
create or replace trigger delete_dept
before delete on DEPT
for each row
begin
delete from EMP where DEPT_NO = :old.DEPT_NO
delete from POS where DEPT_NO = :old.DEPT_NO
end
/
方法二:修改你的外键设置,达到级联删除的目的,具体实现如下:
a)先查询出EMP表和POS表中 外键的名称(如果你知道 外键名这一步可以省略)
select CONSTRAINT_NAME,TABLE_NAME from user_constraints where CONSTRAINT_TYPE ='R' and TABLE_NAME in('EMP','POS')
b)删除EMP表和POS表上的外键后 重新建立允许级联删除的外键模式
alter table EMP drop constraint 外键名
alter table POS drop constraint 外键名
alter table EMP add constraint 外键名 foreign key(DEPT_NO) references DEPT(DEPT_NO) on delete cascade
alter table POS add constraint 外键名 foreign key(DEPT_NO) references DEPT(DEPT_NO) on delete cascade
---
以上,希望对你有所帮助。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)