create or replace package pkg_test 
as
type cur_test is ref cursor; -- 定義一個cursor的type
end pkg_test;
/
create or replace procedure p_test
(
v_cur out pkg_test.cur_test
)
as
v_sql varchar2(100); -- 
begin
v_sql := 'select a1,a2 from test';
OPEN v_cur FOR v_sql; --
exception
when others then 
DBMS_OUTPUT.PUT_LINE('Error ---------------' || sqlcode || ' : ' || sqlerrm ); 
end p_test;
/
Java程式:
……
CallableStatement call = conn.prepareCall("{ call p_test(?) }");
call.registerOutParameter(1, OracleTypes.CURSOR);// 註冊out參數的SQL數據類型
call.execute();
ResultSet rs=(ResultSet)call.getObject(1);// 取得得數据結果集合
while(rs.next())
……
......

解决方案 »

  1.   

    如果在oracle
    中这么写对吗?(v_cur out ref cursor) is
    begin
    select distinct aa into v_cur from mytable;
    end P_Test;
    好像不对哦,哪该怎么写啊?我想在oracle 管理器里边直接建立
      

  2.   

    CREATE OR REPLACE PACKAGE pkg_test
    AS
       TYPE myrctype IS REF CURSOR;   PROCEDURE get (p_id NUMBER, p_rc OUT myrctype);
    END pkg_test;
    /CREATE OR REPLACE PACKAGE BODY pkg_test
    AS
       PROCEDURE get (p_id NUMBER, p_rc OUT myrctype)
       IS
          sqlstr   VARCHAR2 (500);
       BEGIN
          IF p_id = 0 THEN
             OPEN p_rc FOR
                SELECT ID, NAME, sex, address, postcode, birthday
                  FROM student;
          ELSE
             sqlstr :=
                'select id,name,sex,address,postcode,birthday
               from student where id=:w_id';
             OPEN p_rc FOR sqlstr USING p_id;
          END IF;
       END get;
    END pkg_test;
    /declare
      w_rc       pkg_test.myrctype; --定义ref cursor型变量
     
      --定义临时变量,用于显示结果
      w_id       student.id%type;
      w_name     student.name%type;
      w_sex      student.sex%type;
      w_address  student.address%type;
      w_postcode student.postcode%type;
      w_birthday student.birthday%type;
     
    begin
    pkg_test.get(0,w_rc);
    loop
     fetch w_rc into w_id,w_name,w_sex,w_address,w_postcode,w_birthday;
     exit when w_rc%notfound;
     dbms_output.put_line(w_name);
     end loop;
    end;
    /