使用 fetch .. bulk collect into ..时需要注意的是变量的类型为集合类型,因为bulk collect 是批量的从游标中取数
例如:
--定义集合类型
type v_table is table of emp%type;
--定义变量的类型为集合类型
table_name v_table;
--批量从游标中取数
fetch v_cursor bulk collect into
v_table;
如果这样定义变量类型时是否可以使用 fetch .. bulk collect into 呢?
table_name emp.tab_name%type;
答案是不可以的,因为这样定义的变量是一般类型,而不是集合类型。
具体例子参考:
--定义集合类型
type table_type is table of type_change.table_name%type;
type column_type is table of type_change.column_name%type;
--定义游标
cursor v_cursor is
select table_name,column_name from type_change;
--定义集合类型的变量
v_table table_type;
v_column column_type;
--打开游标开始使用
open v_cursor;
--批量的从游标中取数
fetch v_cursor bulk collect into
v_table,
v_column;
--使用for循环开始遍历数据
for i in 1..v_table.count loop
exit when v_cursor%notfound; --循环语句中作为循环结束的判断(记得放在loop语句内)
v_sql:='insert into emp(shu_ju,row_id) as select'||v_column(i),rowid||' from'||v_table(i);
execute immediate v_sql;
commit;
v_sql2:='update '||v_table(i)||' set '||v_column(i)||' is null';
execute immediate v_sql2;
commit;
v_sql3:='alter table '||v_table(i)||' modify '||v_column(i)||' date';
execute immediate v_sql3;
v_sql4:='update 'v_table(i) 'v set '||v_column(i)'=(select shu_ju from emp e where e.row_id=v.rowid)';
execute immediate v_sql4;
commit;
delete from emp;
commit;
end loop;
close v_cursor;--关闭游标