sql >> Base de Datos >  >> RDS >> Oracle

Obtener una matriz pl/sql (como parámetro de salida)

No utilice arreglos asociativos definidos en el ámbito de PL/SQL (es decir, en un paquete), en su lugar, utilice una colección definida en el ámbito de SQL.

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

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

Entonces el paquete es:

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;
/

Pruebas en la base de datos :

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();
}