关联分配游标结果集问题

时间:2019-04-22 03:57:44

标签: java stored-procedures jdbc db2

我正在尝试运行在此链接中找到的这段代码:http://www.sqlines.com/db2-to-oracle/process_result_sets_in_procedures

我很确定运行存储过程时,它会返回所需的值,但是当我将其放入分配“ cur”并获取值时,它什么也不会返回。

CALL MYSTOREDPROC();

ASSOCIATE RESULT SET LOCATOR (result) WITH PROCEDURE MYSTOREDPROC;
ALLOCATE cur CURSOR FOR RESULT SET result;
FETCH cur INTO p_name;
CLOSE cur; 
  1. 我尝试直接将其运行到db2并成功运行,这意味着它可以正常运行,但是我无法确认它是否真正返回了结果集
  2. 我试图通过jdbc调用它,它返回此异常

      

    线程“ main”中的com.ibm.db2.jcc.c.SqlException异常:   [ibm] [db2] [jcc] [10100] [10910]   调用了java.sql.CallableStatement.executeQuery(),但没有结果集   被退回。使用java.sql.CallableStatement.executeUpdate()作为   非查询

我的问题:

我怎么知道“结果”是否真的放在“ cur”中?

这是我调用存储过程的方式:

String ret = "";
statement = connection.prepareCall("{CALL SP_CALLER(?)}");
statement.registerOutParameter(1, java.sql.Types.VARCHAR);
resultSet = statement.executeQuery();   
resultSet.next();
ret = resultSet.getString(1);   
resultSet.close();
closeAllConnection();
return ret;

基于异常,它指出db2,它不返回任何值。

已更新

这是我的存储过程:

CREATE OR REPLACE PROCEDURE ITRS.SP_CALLER()
DYNAMIC RESULT SETS 1

BEGIN

DECLARE loc_cursor RESULT_SET_LOCATOR VARYING;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE v_useraccountid SMALLINT;
DECLARE v_roleid SMALLINT;
DECLARE v_userid VARCHAR(20);
DECLARE v_username VARCHAR(50);
DECLARE v_lastlogindate TIMESTAMP;
DECLARE v_deleted SMALLINT;

DECLARE ret CURSOR WITH RETURN FOR
SELECT * from ITRS.DUMBTABLE where username='JOHN';


CALL ITRS.PR_USERACCOUNTGETALL();

ASSOCIATE RESULT SET LOCATOR (loc_cursor) WITH PROCEDURE ITRS.PR_USERACCOUNTGETALL;
ALLOCATE cur CURSOR FOR RESULT SET loc_cursor;

ins_loop: 
LOOP
FETCH cur INTO v_useraccountid,v_roleid,v_userid,v_username,v_lastlogindate,v_deleted;
  IF SQLSTATE <> '00000' THEN LEAVE ins_loop; END IF;
  INSERT INTO ITRS.DUMBTABLE(USERACCOUNTID,ROLEID,USERID,USERNAME,LASTLOGINDATE,DELETED)
 VALUES(v_useraccountid,v_roleid,v_userid,v_username,v_lastlogindate,v_deleted);
END LOOP ins_loop;

CLOSE cur;
open ret;
END

1 个答案:

答案 0 :(得分:0)

错误的通话顺序。
您应该使用正确的调用从存储过程中检索结果集。
Retrieving a known number of result sets from a stored procedure in a JDBC application

CallableStatement cstmt;
ResultSet rs;
int i;
String s;
…
cstmt.execute();                        // Call the stored procedure       1 
rs = cstmt.getResultSet();              // Get the first result set        2 
while (rs.next()) {                     // Position the cursor             3 
 i = rs.getInt(1);                      // Retrieve current result set value
 System.out.println("Value from first result set = " + i);  
                                        // Print the value
}