oracle存储过程(返回列表的存储结合游标使用)总结 以及在java中的调用

这段时间开始学习写存储过程,主要原因还是因为工作需要吧,本来以为很简单的,但几经挫折,豪气消磨殆尽,但总算搞通了,为了避免后来者少走弯路,特记述与此,同时亦对自己进行鼓励。

以下是我在开发项目中第一次编写的存储,里面用到了嵌套游标和嵌套循环,以及变量的定义方式,第一次不规范的地方还请多多包含,有不明白的地方也可以给我留言,大家互相学习。

--准考证 随机生成 存储过程

--生成规则:在用户选择考试关联好考点和考场之后,点击自动生成准考证,准考证按照 当年考试次数后四位+岗位类型+考点编号+考场编号+座位号 这种规则随机生成

--备注:一个考场下面只能做三十个人,并且不同岗位类型的考生不能在同一考场,但是同一岗位类型的不同岗位可以在同一个考场
--注意1.变量命名的时候不能和字段名一样
create or replace procedure card_random_generate(exam_id in number,examNum in varchar,creater in varchar) as
--定义变量
    exam_stu_num number;--考试下所有考生的数量
    job_name exam_job.jobname%type;--岗位名称
    job_code exam_job.jobcode%type;--岗位编号
    job_type exam_job.jobtype%type;--岗位类型
    job_stu_num number;--每个岗位下报考的考生数量
    
    point_id exam_point.id%type;--考场对应考点的考点id
    point_num exam_point.pointnum%type;--考点编号
    point_name exam_point.pointname%type;--考点名称
    room_num  exam_point.pointnum%type;--考场编号
    room_name  exam_point.pointname%type;--考场名称
    room_id ep_exam_point.id%type;--考场在关联表中对应的id
    room_number number;--每个考试下考场的个数
    studentid exam_student.id%type;--考生的id
    seat_num exam_card.seatnum%type;--座位号
    card_num exam_card.cardnum%type;--准考证号
    i number;--循环变量
    j number;--每个岗位类别需要的考场数
    rn number;
    
   
    
     --定义查询岗位游标 规则:1.按照岗位类型分组 2.统计每个类型处于缴费状态以及审核过的考生的数量 3.岗位状态是正常状态
     CURSOR student_job IS  
         select j.jobtype,count( j.jobtype) as job_stu_num from exam_student e inner join exam_job j on e.examid=exam_id
         and e.jobid=j.id and e.status='6' and e.ispay='1' and e.state='1' and j.status='1'  group by j.jobtype;
    --定义 根据考试id查询关联的考点 和考场信息(按照考点id升序)
     CURSOR exam_point_room IS
     select e.id,p.pointname, p.pointnum,p.parent,p.ptype,(select c.pointnum from exam_point c where c.id=p.parent) as point_number,e.isuser from ep_exam_point e  
     left join exam_point p on e.pointid=p.id or e.centernum=p.id  where examid=exam_id and p.ptype='2' and p.state='1' and e.isuser='1' order by p.id;
     
 begin
  select count(*) into exam_stu_num  from exam_student s  where  examid=exam_id and s.ispay='1' and s.status='6' and s.state='1';--所有已审核,已缴费成功,未生成准考证的考生数量
  dbms_output.put_line('该考试下所有的考生数量是:'||exam_stu_num);
  --一级循环标准  按岗位类型
  for c in student_job loop  
     begin  
       job_type:=c.jobtype;--岗位类型
       job_stu_num:=c.job_stu_num;--每个岗位类型下的考生数量
       if(mod(job_stu_num,30)=0) then
       j:=job_stu_num/30;
       else
       j:=floor(job_stu_num/30)+1;
       end if;
       
       dbms_output.put_line('岗位类型是:'||job_type||',报考岗位的考生数量是:'||job_stu_num||',岗位需要的考场数量是:'||j);
       --二级循环 按照每个岗位下考生的数量
       while job_stu_num>0
        loop
          begin          
           --三级循环标准 按照考场
              for d in exam_point_room loop
                  -- if(d.isuser=2)then
                 --  exit;
                  -- end if;
                begin
                 if(d.ptype=2) then
                     point_num:=d.point_number;
                    -- select id into  point_id from exam_point where id=d.parent;--查询考场的父节点考点的考点id
                     point_id:=d.parent;--考场的父节点考点的考点id
                     room_num:=d.pointnum;
                     room_name:=d.pointname;
                     room_id:=d.id;
                     dbms_output.put_line('考点编号是:'|| point_num||',考场编号是:'||room_num);
                     i:=1;
                     while i<=30  --每个考场座位号都是从01-30
                      loop
                        begin     --这里是取满足状态的学生 随机取一个把生成的准考证与学生id一一对应,在此之前一直非常无奈的是在oracle中要想查询排过序的特定行结果一般都要用到子查询,而在存储过程中

                                     --给变量赋值时候在子查询里面赋值一直不能编译成功,几经尝试后来放在外面把子查询作为一个整体在外面实现了赋值功能,好坑啊,不过最终还是实现了,呵呵
                           select  b.id into  studentid   from    (select s.* ,rownum as rn from exam_student s inner join exam_job j on s.jobid=j.id and s.examid=j.examid
                           and s.status='6' and s.state='1' and s.ispay='1' where s.examid=exam_id and j.jobtype=job_type) b where rn=job_stu_num ;
                           dbms_output.put_line('考生id是:'||studentid);
                          if(i<10) then
                            dbms_output.put_line('准考证号是:'|| examNum||job_type||point_num||room_num||'0'||i||',考场名称是:'||room_name);
                            card_num:=examNum||job_type||point_num||room_num||'0'||i;--拼接准考证号
                            seat_num:='0'||i;
                            insert into exam_card values(seq_exam_card_id.nextval,exam_id,studentid,point_id,room_num,seat_num,card_num,creater,sysdate);
                            commit;
                          else
                            dbms_output.put_line('准考证号是:'|| examNum||job_type||point_num||room_num||i||',考场名称是:'||room_name);
                            card_num:=examNum||job_type||point_num||room_num||i;--拼接准考证号
                            seat_num:=i;
                            insert into exam_card values(seq_exam_card_id.nextval,exam_id,studentid,point_id,room_num,seat_num,card_num,creater,sysdate);
                            commit;
                          end if;
                           update exam_student set status='7' where id=studentid;--改变学生的状态为7 生成准考证状态
                           commit;
                          i:=i+1;
                          job_stu_num:=job_stu_num-1;
                        end;
                        if(job_stu_num<=0) then
                        update ep_exam_point set isuser='2' where id=room_id;
                        commit;
                        exit;--退出循环
                        end if;
                      end loop;
                  end if;
                 
                end;
                   if(job_stu_num=0)then
                   exit;--退出循环
                   end if;
                  if(job_stu_num>0) then
                        update ep_exam_point set isuser='2' where id=room_id;
                        commit;
                        exit;--退出循环(此时一个考场排满了,退出循环进入下一个考场继续排)
                  end if;
                  
              end loop;
            
          
          end;
        end loop;
      end;
  end loop;
end card_random_generate;

一:无返回值的存储过程
存储过程为:
CREATE OR REPLACE PROCEDURE TESTA(PARA1 IN VARCHAR2,PARA2 IN VARCHAR2) AS
BEGIN
   INSERT INTO HYQ.B_ID (I_ID,I_NAME) VALUES (PARA1, PARA2);
END TESTA;
 
然后呢,在java里调用时就用下面的代码:
package com.hyq.src;
 
import java.sql.*;
import java.sql.ResultSet;
 
public class TestProcedureOne {
 public TestProcedureOne() {
 }
 public static void main(String[] args ){
    String driver = "oracle.jdbc.driver.OracleDriver";
    String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521: hyq ";
    Statement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
    CallableStatement cstmt = null;
 
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(strUrl, " hyq ", " hyq ");
      CallableStatement proc = null; //创建执行存储过程的对象
      proc = conn.prepareCall("{ call HYQ.TESTA(?,?) }"); //设置存储过程 call为关键字.
      proc.setString(1, "100"); //设置第一个输入参数
      proc.setString(2, "TestOne");//设置第二个输入参数
      proc.execute();//执行
    }
    catch (SQLException ex2) {
      ex2.printStackTrace();
    }
    catch (Exception ex2) {
      ex2.printStackTrace();
    }
    finally{
      try {
        if(rs != null){
          rs.close();
          if(stmt!=null){
            stmt.close();
          }
          if(conn!=null){
            conn.close();
          }
        }
      }
      catch (SQLException ex1) {
      }
    }
 }
}
当然了,这就先要求要建张表TESTTB,里面两个字段(I_ID,I_NAME)。
 
二:有返回值的存储过程(非列表)
存储过程为:
CREATE OR REPLACE PROCEDURE TESTB(PARA1 IN VARCHAR2,PARA2 OUT VARCHAR2) AS
BEGIN
   SELECT INTO PARA2 FROM TESTTB WHERE I_ID= PARA1;
END TESTB;
在java里调用时就用下面的代码:
package com.hyq.src;
 
public class TestProcedureTWO {
 public TestProcedureTWO() {
 }
 public static void main(String[] args ){
    String driver = "oracle.jdbc.driver.OracleDriver";
    String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:hyq";
    Statement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(strUrl, " hyq ", " hyq ");
      CallableStatement proc = null;
      proc = conn.prepareCall("{ call HYQ.TESTB(?,?) }"); //设置存储过程
      proc.setString(1, "100");//设置第一个参数输入参数
      proc.registerOutParameter(2, Types.VARCHAR);//第二个参数输出参数,是VARCHAR类型的
      proc.execute();//执行
      String testPrint = proc.getString(2);//获得输出参数
      System.out.println("=testPrint=is="+testPrint);
    }
    catch (SQLException ex2) {
      ex2.printStackTrace();
    }
    catch (Exception ex2) {
      ex2.printStackTrace();
    }
    finally{
      try {
        if(rs != null){
          rs.close();
          if(stmt!=null){
            stmt.close();
          }
          if(conn!=null){
            conn.close();
          }
        }
      }
      catch (SQLException ex1) {
      }
    }
 }
}
 
}
注意,这里的proc.getString(2)中的数值2并非任意的,而是和存储过程中的out列对应的,如果out是在第一个位置,那就是proc.getString(1),如果是第三个位置,就是proc.getString(3),当然也可以同时有多个返回值,那就是再多加几个out参数了。
 
三:返回列表(存储的参数是out 游标)
由于oracle存储过程没有返回值,它的所有返回值都是通过out参数来替代的,列表同样也不例外,但由于是集合,所以不能用一般的参数,必须要用pagkage了.所以要分两部分
1, 建一个程序包。如下:
CREATE OR REPLACE PACKAGE TESTPACKAGE  AS
 TYPE Test_CURSOR IS REF CURSOR;
end TESTPACKAGE;
2,建立存储过程,存储过程为:
CREATE OR REPLACE PROCEDURE TESTC(p_CURSOR out TESTPACKAGE.Test_CURSOR) IS
BEGIN
    OPEN p_CURSOR FOR SELECT * FROM HYQ.TESTTB;
END TESTC;
可以看到,它是把游标(可以理解为一个指针),作为一个out 参数来返回值的。
在java里调用时就用下面的代码:
package com.hyq.src;
import java.sql.*;
import java.io.OutputStream;
import java.io.Writer;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import oracle.jdbc.driver.*;
 
 
public class TestProcedureTHREE {
 public TestProcedureTHREE() {
 }
 public static void main(String[] args ){
    String driver = "oracle.jdbc.driver.OracleDriver";
    String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:hyq";
    Statement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
 
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(strUrl, "hyq", "hyq");
 
      CallableStatement proc = null;
      proc = conn.prepareCall("{ call hyq.testc(?) }"); //存储过程 hyq包下的
      proc.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);//设置输出参数是一个游标.第一个参数,游标类型
      proc.execute();//执行
      rs = (ResultSet)proc.getObject(1); //获得第一个参数是一个游标,转化成ResultSet类型
 
      while(rs.next()) //获得数据
      {
          System.out.println("<tr><td>" + rs.getString(1) + "</td><td>"+rs.getString(2)+"</td></tr>");
      }
    }
    catch (SQLException ex2) {
      ex2.printStackTrace();
    }
    catch (Exception ex2) {
      ex2.printStackTrace();
    }
    finally{
      try {
        if(rs != null){
          rs.close();
          if(stmt!=null){
            stmt.close();
          }
          if(conn!=null){
            conn.close();
          }
        }
      }
      catch (SQLException ex1) {
      }
    }
 }
}
在这里要注意,在执行前一定要先把oracle的驱动包放到class路径里,否则会报错的。
原文地址:https://www.cnblogs.com/weiyi1314/p/6572538.html