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

时间:2014-02-03 07:39:06

标签: oracle plsql plsqldeveloper

表名:T_record

Id(auto increment using sequence)    Name      Age
1                                    Chitta    18
2                                    Chitta1   19
3                                    Chitta2   18
4                                    Chitta3   18

我有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;

但是批量收集不起作用。

我如何了解新插入的id(我希望它在其他选择查询中使用相同的id)?

1 个答案:

答案 0 :(得分:7)

不,你不能让它以那种方式工作。仅当returning语句使用insert子句时,才能使用values(非批量收集)子句。

您可以使用此类工作来获取id s:

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

/* 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
) ;

Pl / SQL Block:

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;
/ 

结果:

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