Oracle
 sql >> Database >  >> RDS >> Oracle

Recupero di un array pl/sql (come parametro out)

Non utilizzare array associativi definiti nell'ambito PL/SQL (cioè in un pacchetto) utilizza invece una raccolta definita nell'ambito SQL.

create or replace TYPE stringlist IS TABLE OF VARCHAR2(4000);
/

create or replace TYPE stringlist2 IS TABLE OF VARCHAR2(4000);
/

Allora il pacchetto è:

CREATE OR REPLACE PACKAGE mypackage
AS
  PROCEDURE table_in_table_out(
    inputArray   IN  stringlist,
    outputArray  OUT stringlist2,
    resultString OUT VARCHAR2
  );
END mypackage;
/

CREATE OR REPLACE PACKAGE BODY mypackage
AS
  PROCEDURE table_in_table_out(
    inputArray   IN  stringlist,
    outputArray  OUT stringlist2,
    resultString OUT VARCHAR2
  )
  IS
    i BINARY_INTEGER;
  BEGIN
    IF inputArray IS NULL THEN
      RETURN;
    END IF;
    outputArray := stringlist2();
    IF inputArray IS EMPTY THEN
      RETURN;
    END IF;

    -- Handle sparse arrays
    i := inputArray.FIRST;
    LOOP
      outputArray.EXTEND;
      outputArray(outputArray.LAST) := inputArray(i);
      resultString := resultString || inputArray(i);
      EXIT WHEN i = inputArray.LAST; 
      i := inputArray.NEXT(i);
    END LOOP;
  END;
END mypackage;
/

Test nel database :

SET SERVEROUTPUT ON;

DECLARE
  i stringList := StringList( 'A', 'C', 'F' );
  e stringlist2;
  s VARCHAR2(4000);
  n BINARY_INTEGER;
BEGIN
  i.DELETE(2);
  n := i.FIRST;
  LOOP
    DBMS_OUTPUT.PUT_LINE( n || ': ' || i(n) );
    EXIT WHEN n = i.LAST;
    n := i.NEXT(n);
  END LOOP;
  mypackage.table_in_table_out( i, e, s );
  DBMS_OUTPUT.PUT_LINE( s );
  n := e.FIRST;
  LOOP
    DBMS_OUTPUT.PUT_LINE( n || ': ' || e(n) );
    EXIT WHEN n = e.LAST;
    n := e.NEXT(n);
  END LOOP;
END;
/

Java :

try{
  Class.forName( "oracle.jdbc.OracleDriver" );

  Connection con = DriverManager.getConnection(
      "jdbc:oracle:thin:@localhost:1521:orcl",
      "username",
      "password"
  );

  OracleConnection oCon = (OracleConnection) con;

  OracleCallableStatement st = (OracleCallableStatement) con.prepareCall( "{ call mypackage.table_in_table_out( :chars, :ergs, :res )}" );

  ARRAY ia = oCon.createARRAY("STRINGLIST", new String[]{ "A", "C", "F"} );
  st.setARRAYAtName("chars", ia );
  st.registerOutParameter( 2, java.sql.Types.ARRAY, "VARCHAR2S_TABLE" );
  st.registerOutParameter( 3, java.sql.Types.VARCHAR );

  System.out.println( st.execute() );
  System.out.println( st.getString( 3 ) );
  String[] strs = (String[]) st.getARRAY(2).getArray();

  for ( String str : strs )
    System.out.println(str);

  st.close();
  con.close();
} catch (ClassNotFoundException | SQLException ex) {
  System.out.println( ex.getMessage() );
  ex.printStackTrace();
}