gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:58:39 24 4
gpt4 key购买 nike

表名: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)?

最佳答案

不,您无法让它以这种方式工作。仅当 insert 语句使用 values 子句时,您才可以使用 returning(不是批量收集)子句。

您可以使用这种解决方法来获取那些 id:

您首先用要插入的值填充一个集合,然后使用 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

关于Oracle:使用 select 插入不返回批量收集新插入的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21521987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com