存储过程:SQL代码

  1. create or replace procedure p_rpt_test is  
  2.   /**********************************************************************************   
  3.   NAME:       p_rpt_test    
  4.   PURPOSE:    报表数据测试   
  5.      
  6.   REVISIONS:   
  7.   Ver        Date         Author                 Description   
  8.   ---------  ----------  ----------------------  ------------------------------------   
  9.   V1.0       2012-09-12   WangXL 12345        1.创建此存储过程   
  10.      
  11.   RETURN:   无返回值   
  12.      
  13.   NOTES:   1、使用到不带参数的游标(即cursor)   
  14.            2、使用到for in loop end loop循环   
  15.            3、游标打开后,必须关闭。   
  16.      
  17.   **********************************************************************************/   
  18.   /*按照规划,定义number,string,date三种类型变量名称*/   
  19.   i_id          number(8);   
  20.   str_testname  varchar2(30);   
  21.   dt_createdate date;   
  22.   /*按照规划,定义cursor变量名称,游标是一个查询结果集,可以传入变量参数,也可以不传。   
  23.   这里的结果集是test1表的三个字段*/   
  24.   cursor cur_test1 is  
  25.     select a.id, a.testname, a.createtime from test1 a;   
  26.   
  27. begin  
  28.   
  29.   /* for in loop end loop 循环体 */   
  30.   for c in cur_test1 loop   
  31.     -- 该循环体中,游标自动打开关闭,不需要手工打开再关闭。   
  32.      
  33.     -- c 是循环内部变量,为了开发方便,所以简单命名为c。   
  34.     -- c 根据循环,依次读取游标cur_test1的每一行记录。   
  35.      
  36.     --如果数据量很大,使用其他的方式取游标记录,如bulk collect into   
  37.     i_id          := c.id; --赋值游标中一行记录的id列值到i_id变量上   
  38.     str_testname  := c.testname || 'xx'; --将游标中一行记录的testname列值加上'xxx'处理后赋值到str_testname变量上   
  39.     dt_createdate := c.createtime - 2;   
  40.      
  41.     insert into test2   
  42.       (id, testname, createtime)   
  43.     values  
  44.       (i_id, str_testname, dt_createdate); --将变量值插入到test2表中   
  45.      
  46.   end loop;   
  47.   
  48.   commit; --所有记录插入后,一次性提交。   
  49.   
  50.   
  51.   
  52.   open cur_test1; --打开定义好的游标(cursor)   
  53.   
  54.   /*loop end loop循环体*/   
  55.   
  56.   loop   
  57.     fetch cur_test1   
  58.       into i_id, str_testname, dt_createdate;   
  59.     --fetch就是取游标中一行记录到三个变量中   
  60.     exit when cur_test1%notfound; --如果游标已经没有记录了,那么%notfound就是true,从而退出循环;如果还有记录继续下一步   
  61.      
  62.     str_testname  := str_testname || 'yy'; --将游标中一行记录的testname列值加上'xxx'处理后赋值到str_testname变量上   
  63.     dt_createdate := dt_createdate + 2;   
  64.      
  65.     insert into test2   
  66.       (id, testname, createtime)   
  67.     values  
  68.       (i_id, str_testname, dt_createdate); --将变量值插入到test2表中   
  69.      
  70.   end loop;   
  71.   
  72.   commit; --所有记录插入后,一次性提交。   
  73.   close cur_test1; --关闭开头打开的游标   
  74. exception   
  75.   when others then  
  76.     rollback; --如果上面操作失败,主动使用rollback取消所有的操作。   
  77.     dbms_output.put_line(sqlerrm);   
  78. end;  
原文地址:https://www.cnblogs.com/chuchudongderen/p/3192584.html