Execute anonymous pl/sql block and get resultset in java

前端 未结 3 1022
-上瘾入骨i
-上瘾入骨i 2020-11-28 09:15

I would like to execute the anonymous PL/SQL and need to get the resultset object. I got the code which can be done by using cursors inside the PL/SQL block.

But the

3条回答
  •  一生所求
    2020-11-28 09:52

    First off, the code you posted is not valid. An anonymous PL/SQL block cannot return an expression. And no PL/SQL block can return the result of a query like that. You would need to do something like declaring a REF CURSOR and opening that cursor using the various SQL statements.

    Since an anonymous PL/SQL block cannot return anything to a caller, the architecture you're describing is a problematic. At a minimum, you'd need to modify the anonymous block so that there was a bind variable that your JDBC code could register. Something like (adapted from an example in Menon's Expert Oracle JDBC Programming (note that I may have introduced some minor syntax errors)

    CallableStatement stmt := null;
    ResultSet         rset := null;
    String            query := 'DECLARE 
                                  FUNCTION get_result
                                    RETURN SYS_REFCURSOR
                                  AS
                                    l_rc SYS_REFCURSOR;
                                  BEGIN
                                    OPEN l_rc 
                                     FOR SELECT DISTINCT fundname d, fundname r
                                           FROM some_table
                                          WHERE some_condition
                                          ORDER BY 1;
                                    RETURN l_rc;
                                  EXCEPTION
                                    WHEN others THEN
                                      OPEN l_rc 
                                       FOR SELECT 'Not Available' d, 'Not Available' r
                                             FROM dual;
                                      RETURN l_rc;
                                  END get_result;
                                BEGIN
                                  ? := get_result;
                                END;';
    try {
      cstmt := conn.prepareCall( query );
      cstmt.registerOutParameter( 1, OracleTypes.CURSOR );
      cstmt.execute();
      rset := (ResultSet) cstmt.getObject( 1 );
    }
    finally {
      <>
    }
    

提交回复
热议问题