Oracle 中的 FORALL 语句


当要在 Oracle 中之心批量 INSERT、UPDATE 和 DELETE 操作时,可以使用 FORALL 语句。

语法:

  1. --语法1:   
  2. FORALL 下标变量(只能当作下标被引用) IN 下限..上限   
  3.   sql 语句;    --只允许一条 sql 语句   
  4.   
  5.   
  6. --语法2:   
  7. FORALL 下标变量 IN INDICES OF(跳过没有赋值的元素,例如被 DELETE 的元素,NULL 也算值) 集合   
  8.   [BETWEEN 下限 AND 上限]   
  9.   sql 语句;   
  10.   
  11.   
  12. --语法3:   
  13. FORALL 下标变量 IN VALUES OF 集合(把该集合中的值当作下标变量)   
  14.   sql 语句;  

 

  1. create table tb1(   
  2.   id number(5),   
  3.   name varchar2(50)   
  4. );  

语法1演示:

  1. --批量插入演示   
  2. declare  
  3.   type tb_table_type is table of tb1%rowtype   
  4.     index by binary_integer;   
  5.   tb_table tb_table_type;   
  6. begin  
  7.   for i in 1..10 loop   
  8.     tb_table(i).id:=i;   
  9.     tb_table(i).name:='NAME'||i;   
  10.   end loop;   
  11.   forall i in 1..tb_table.count  
  12.     insert into tb1 values tb_table(i);   
  13. end;   
  14.   
  15.   
  16. --批量修改演示   
  17. declare  
  18.   type tb_table_type is table of tb1%rowtype   
  19.   index by binary_integer;   
  20.   tb_table tb_table_type;   
  21. begin  
  22.   for i in 1..10 loop   
  23.     tb_table(i).id:=i;   
  24.     tb_table(i).name:='NAMES'||i;   
  25.   end loop;   
  26.   forall i in 1..tb_table.count  
  27.     update tb1 t set row = tb_table(i) where t.id = tb_table(i).id;   
  28. end;   
  29.   
  30.   
  31. --批量删除演示   
  32. declare  
  33.   type tb_table_type is table of tb1%rowtype   
  34.   index by binary_integer;   
  35.   tb_table tb_table_type;   
  36. begin  
  37.   for i in 1..10 loop   
  38.     tb_table(i).id:=i;   
  39.     tb_table(i).name:='NAMES'||i;   
  40.   end loop;   
  41.   forall i in 1..tb_table.count  
  42.     delete tb1 where id = tb_table(i).id;   
  43. end;  

更多Oracle相关信息见Oracle 专题页面 http://www.bkjia.com/topicnews.aspx?tid=12

相关内容