【问题标题】:Insert into dependent tables using triggers in Oracle database 11g在 Oracle 数据库 11g 中使用触发器插入依赖表
【发布时间】:2018-12-20 04:07:53
【问题描述】:

例如,我使用 3 个表:A、B 和 C

我正在表 A 上创建触发器。所以在触发器内部,我将一条记录插入到表 B 中(作为 C 的主人),然后我需要将另一条记录插入到表 C 中强>。

我在 A 表上使用触发器,因为我需要使用 A 表中的值来创建表 B 中的记录,然后我使用信息将新记录插入到表 C 中。

在将第一条记录插入到表 B 中后,我使用截断的代码“RETURNING new_B_Id INTO b_lastid;”来获取新插入的id,但是当我尝试插入到表C中时,会抛出此消息:

B 上不存在主记录。

有解决办法吗?

【问题讨论】:

  • 发布表结构,让我知道您在触发器中处理的所有异常是什么
  • “表上不存在主记录”不是 Oracle 错误。这不是文学课,不要“发明”你自己的错误消息——复制/粘贴 Oracle 报告的内容(ORA-xxxxx 错误代码会有所帮助)。
  • 您所概述的是应该工作的那种方法,所以问题将在细节中。不幸的是,只有您可以看到您的代码,因此我们无能为力。如果你不能发现你的灯笼裤,你需要发布一个可重现的测试用例——它不必是完整的表结构,只是证明问题所必需的最低限度。通常情况下,简化代码以发布的练习会导致我们发现错误的灯泡时刻。

标签: oracle oracle11g triggers insert foreign-keys


【解决方案1】:

举个例子,这里有一个最简单的方法,它可能有效并且确实有效:a sqlfiddle demo to prove it

create table a (a_id number  primary key
                , txt varchar2(24))
/
create table b (b_id number  primary key
                 , a_id number not null
                 , constraint b_a_fk foreign key (a_id) references a)
/
create table c (c_id number primary key
                , b_id number not null
                , constraint c_b_fk foreign key (b_id) references b)
/
create sequence a_seq start with 10
/
create sequence b_seq start with 20
/
create sequence c_seq start with 30
/

create or replace trigger a_trg
after insert on a for each row
declare
    new_b_id number;
begin
    insert into b (b_id, a_id) values (b_seq.nextval, :new.a_id)
    returning b_id into new_b_id;     
    insert into c (c_id, b_id) values (c_seq.nextval, new_b_id);
end;
/

因此,您遇到的问题将在于我在上面发布的内容与您自己的代码中的内容之间的差距。由于问题似乎是在插入C 时出现ORA-02291: integrity constraint,我会仔细查看您在该表上定义的外键约束:它真的引用B 上的主键吗?

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2014-06-21
    相关资源
    最近更新 更多