是否可以将插入键上的主键作为选择语句返回-Oracle?

问题描述 投票:1回答:2

因此,通常在使用触发器时,我通常如下获得新插入记录的主键。

插入表1(pk1,注释)中的值(空,“测试器”),返回pk1进入v_item;

我正在尝试使用相同的概念,但使用select语句插入。因此,例如:

插入表1(pk1,注释)中,选择null,从表2中进行描述,其中pk2 = 2,返回pk1进入v_item;

注意:1. table1上有一个触发器,该触发器会在插入时自动创建一个pk1。2.由于要插入的表的大小,我需要使用选择插入。3.插入基本上是记录的副本,因此一次仅插入1条记录。

让我知道是否可以提供更多信息。

oracle oracle-apex sql-insert database-trigger
2个回答
0
投票

我不相信您可以直接通过插入/选择来做到这一点。但是,您可以使用PL / SQL和FORALL进行操作。考虑到表大小的限制,您必须使用l_limit来平衡内存使用量和性能。这是一个例子...

赋予该表100行:

create table t (
  c  number generated by default as identity,
  c2 number
);

insert into t (c2)
select rownum
from dual
connect by rownum <= 100;

您可以这样做:

declare

  cursor t_cur
  is
    select c2
    from t;

  type t_ntt is table of number;

  l_c2_vals_in t_ntt;
  l_c_vals_out t_ntt;
  l_limit      number := 10;

begin

  open t_cur;

  loop
    fetch t_cur bulk collect into l_c2_vals_in limit l_limit;

    forall i in indices of l_c2_vals_in
    insert into t (c2) values (l_c2_vals_in(i))
    returning c bulk collect into l_c_vals_out;

    -- You have access to the new ids here
    dbms_output.put_line(l_c_vals_out.count);

    exit when l_c2_vals_in.count < l_limit;
  end loop;

  close t_cur;

end;

0
投票

您不能使用该机制; as shown in the documentation铁路图:

“插入语法”

返回子句只允许使用值版本,而不允许子查询版本。

我将您的第二个限制解释为您必须处理的列数,可能是作为单个变量。但是有很多方法可以避免这种情况。您可以先选择一个行类型变量:

declare
  v_item number;
  v_row table1%rowtype;
begin
  ...
  select null, description
  into v_row
  from table2 where pk2 = 2;

  insert into table1 values v_row returning pk1 into v_item;

  dbms_output.put_line(v_item);
  ...

或带有循环,如果您只真正有一行,这可能会使事情看起来比必要的事情复杂:

declare
  v_item number;
begin
  ...
  for r in (
    select description
    from table2 where pk2 = 2
  )
  loop
    insert into table1 (notes) values (r.description) returning pk1 into v_item;
    dbms_output.put_line(v_item);
    ...
  end loop;
  ...

或带有收藏夹...如@Dan在回答此问题时所发布的,因此不再重复! -不过,对于单行来说,这可能会过大或过于复杂。

© www.soinside.com 2019 - 2024. All rights reserved.