Oracle:使用select插入不返回批量收集新插入的ID

Chi*_*jan 1 oracle plsql plsqldeveloper

表名: T_record

Id(auto increment using sequence)    Name      Age
1                                    Chitta    18
2                                    Chitta1   19
3                                    Chitta2   18
4                                    Chitta3   18
Run Code Online (Sandbox Code Playgroud)

我有PL/SQL程序,它将在上表中插入记录.

Insert into T_record (name, Age) 
  (select  name, age 
     from T_record 
    where Age =18) 
   returning  id bulk collect into v_newly_added_conf_input_ids;
Run Code Online (Sandbox Code Playgroud)

但批量收集不起作用.

我怎样才能知道id新插入的s(我希望它id在其他选择查询中使用相同的s)?

Nic*_*nov 7

不,你不能让它以这种方式工作.returning只有在insert使用statement values子句时才能使用(非批量收集)子句.

你可以使用这种工作来获得那些id:

首先使用要插入的值填充集合,然后使用forall构造插入数据并将ids 返回到另一个集合中:

/* identity column is a 12c feature. In prior versions you use 
   sequences - not the main point here. Use it just to save time.
 */   
create table t1(
  t1_id number generated as identity primary key,
  name1 varchar2(31),
  age   number
) ;
Run Code Online (Sandbox Code Playgroud)

Pl/SQL块:

declare
  /* record */
  type t_rec is record(
    name1 varchar2(32),
    age   number  -- as a side note, it's better to store 
  );              -- date of birth not the age - not that dependable.

  type t_source_list is table of t_rec;
  type t_id_list     is table of number;

  l_source_list t_source_list; -- source collection
  l_id_list     t_id_list;     -- collection we are going to put IDs into
begin

  /* data we are going to insert 
    replace this query with yours */
  select dbms_random.string('l', 7)
       , level
    bulk collect into l_source_list
   from dual
  connect by level <= 11;

  /* insert data and return IDs into l_id_list collection */
  forall i in l_source_list.first..l_source_list.last
    insert into t1(name1, age) 
       values(l_source_list(i).name1, l_source_list(i).age)
    returning t1_id bulk collect into l_id_list;

  /* print the list of new IDs. */
   for i in l_id_list.first .. l_id_list.last loop
     dbms_output.put_line('ID #' || to_char(I)||':  '||to_char(l_id_list(i)));
   end loop;  
end;
/ 
Run Code Online (Sandbox Code Playgroud)

结果:

anonymous block completed
ID #1:  1
ID #2:  2
ID #3:  3
ID #4:  4
ID #5:  5
ID #6:  6
ID #7:  7
ID #8:  8
ID #9:  9
ID #10: 10
ID #11: 11
Run Code Online (Sandbox Code Playgroud)