gle*_*roo 1 oracle constraints foreign-keys delete-row
我正在使用Oracle 10g Express并尝试从具有双向约束的表中删除记录.我试图解开数百个表和通过Hibernate生成的依赖项(此时无法更改),但这是一个非常简化的示例:
create table TableA (id number(19,0) not null, ..., rTableA_id number(19,0), primary key (id));
create table TableB (id number(19,0) not null, ..., rTableB_id number(19,0), primary key (id));
alter table TableA add constraint FKA1 foreign key (rTableA_id) references TableB;
alter table TableB add constraint FKB1 foreign key (rTableB_id) references TableA;
Run Code Online (Sandbox Code Playgroud)
尝试从任一表中删除条目将返回以下内容:
编辑:在我的情况下,这种情况发生在外键上,前缀为SYS_
ORA-02292: integrity constraint (XXX.FKA1) violated - child record found
Run Code Online (Sandbox Code Playgroud)
我也尝试禁用约束,但所有尝试都是徒劳的:
ORA-02297: cannot disable constraint (XXX.FKA1) - dependencies exist
Run Code Online (Sandbox Code Playgroud)
我不得不想知道你的数据是如何在这个状态下进入的,因为你的外键是not null.如果两个表都是空的,那么你就永远无法在任何一个表中插入一行.
暂时忽略这一点,重新创建场景,我没有问题禁用约束:
CREATE TABLE tablea(id NUMBER(19, 0) NOT NULL,
rtablea_id NUMBER(19, 0) NOT NULL,
PRIMARY KEY(id))
/
CREATE TABLE tableb(id NUMBER(19, 0) NOT NULL,
rtableb_id NUMBER(19, 0) NOT NULL,
PRIMARY KEY(id))
/
INSERT INTO tablea
VALUES (1, 2)
/
INSERT INTO tableb
VALUES (2, 1)
/
ALTER TABLE tablea ADD CONSTRAINT fka1
FOREIGN KEY (rtablea_id)
REFERENCES tableb
/
ALTER TABLE tableb ADD CONSTRAINT fkb1
FOREIGN KEY (rtableb_id)
REFERENCES tablea
/
ALTER TABLE tablea MODIFY CONSTRAINT fka1 DISABLE
/
ALTER TABLE tableb MODIFY CONSTRAINT fkb1 DISABLE
/
delete tablea
/
delete tableb
/
commit
/
Run Code Online (Sandbox Code Playgroud)
结果:
Table created.
Table created.
1 row created.
1 row created.
Table altered.
Table altered.
Table altered.
Table altered.
1 row deleted.
1 row deleted.
Commit complete.
Run Code Online (Sandbox Code Playgroud)
我不确定ORA-02297在尝试禁用外键时是如何出错的.当禁用外键所依赖的主键或唯一键时,通常会看到该错误.
我怀疑你真正想做的是设置约束initially deferred.这将允许您单独执行对每个表的插入和删除,只要在提交事务之前更新或删除相应的行:
CREATE TABLE tablea(id NUMBER(19, 0) NOT NULL,
rtablea_id NUMBER(19, 0) NOT NULL,
PRIMARY KEY(id))
/
CREATE TABLE tableb(id NUMBER(19, 0) NOT NULL,
rtableb_id NUMBER(19, 0) NOT NULL,
PRIMARY KEY(id))
/
ALTER TABLE tablea ADD CONSTRAINT fka1
FOREIGN KEY (rtablea_id)
REFERENCES tableb
INITIALLY DEFERRED
/
ALTER TABLE tableb ADD CONSTRAINT fkb1
FOREIGN KEY (rtableb_id)
REFERENCES tablea
INITIALLY DEFERRED
/
INSERT INTO tablea
VALUES (1, 2)
/
INSERT INTO tableb
VALUES (2, 1)
/
INSERT INTO tableb
VALUES (3, 1)
/
COMMIT
/
DELETE tableb
WHERE id = 2
/
UPDATE tablea
SET rtablea_id = 3
WHERE id = 1
/
COMMIT
/
Run Code Online (Sandbox Code Playgroud)
结果:
Table created.
Table created.
Table altered.
Table altered.
1 row created.
1 row created.
1 row created.
Commit complete.
1 row deleted.
1 row updated.
Commit complete.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3764 次 |
| 最近记录: |