DECLARE
--定义游标并插入数据
CURSOR CUR_OBJECT_FORALL IS SELECT UUID FROM TEST;
--定义forall对象数据 定义的是列对象 即UUID列
TYPE T_OBJECT_FORALL IS TABLE OF CUR_OBJECT_FORALL%ROWTYPE INDEX BY BINARY_INTEGER;
--定义forall实例
T_OBJECT_FORALL1 T_OBJECT_FORALL;
BEGIN
--打开游标
OPEN CUR_OBJECT_FORALL;
--把游标数据放入forall实例中
FETCH CUR_OBJECT_FORALL BULK COLLECT INTO T_OBJECT_FORALL1;
--关闭游标
CLOSE CUR_OBJECT_FORALL;
--循环遍历forall实例并批量插入数据库
FORALL I IN T_OBJECT_FORALL1.FIRST .. T_OBJECT_FORALL1.LAST
INSERT INTO FORALLTEST VALUES T_OBJECT_FORALL1 (I);
COMMIT;
END;
--测试表1
drop table test1;
create table test1(id number(10),name varchar2(10));
insert into test1 values(1,'aa');
insert into test1 values(2,'bb');
commit;
--测试表2
drop table test2;
create table test2(id number(10),name varchar2(10));
--test1
declare
type dr_type is table of test1%ROWTYPE index by binary_integer;
dr_table dr_type;
begin
select id, name BULK COLLECT into dr_table from test1;
FORALL i IN dr_table.first .. dr_table.last
insert into test2 values dr_table (i);
--error statement
--1.insert into test2 values(dr_table(i));报没有足够的值错误,此处外面不可以加括号,当有多个字段的时候,单个字段可以加括号
--2.insert into test2 values(dr_table(i).id,dr_table(i).name);集合的field不可以在forall中使用,必须是整体使用
--3.insert into test2 values dr_table(i+1);错误,不可以对索引变量进行运算
--4.insert into test2 values dr_table(i);dbms_output.put_line(i);不正确,找不到i,因为forall中只能使用单条语句可以引用索引变量
end;