Oracle
 sql >> Base de données >  >> RDS >> Oracle

Requête séparée par des virgules pour plusieurs paramètres dans PLSQL

Utiliser une collection :

CREATE OR REPLACE PROCEDURE RQUERY1
(
 I_PRODUCT IN  SYS.ODCIVARCHAR2LIST,
 I_MODEL   IN  SYS.ODCIVARCHAR2LIST,
 I_TYPE    IN  SYS.ODCIVARCHAR2LIST,
 O_Cursor  OUT SYS_REFCURSOR
)
AS
BEGIN
  OPEN O_Cursor FOR
  SELECT t.*
  FROM   table1 t
         INNER JOIN TABLE( I_PRODUCT ) p ON t.PRODUCT = p.COLUMN_VALUE
         INNER JOIN TABLE( I_MODEL   ) m ON t.MODEL   = m.COLUMN_VALUE
         INNER JOIN TABLE( I_TYPE    ) y ON t.TYPE    = y.COLUMN_VALUE;
END RQUERY1;
/

Ensuite, vous pouvez l'appeler en Java comme ceci :

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.internal.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor; 

public class TestDatabase {
    public static void main(String args[]){
        try{

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

            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@url:port:sid","UserName","Password");

            String[] products = { "Product1", "Product2", "Product3" };
            String[] models   = { "Model1", "Model2", "Model3" };
            String[] types    = { "Type1", "Type2", "Type3" };

            ArrayDescriptor des = ArrayDescriptor.createDescriptor("SYS.ODCIVARCHAR2LIST", con);

            CallableStatement st = con.prepareCall("call TEST.RQUERY1(?,?,?,?)");

            st.setArray( 1, new ARRAY( des, con, products ) );
            st.setArray( 2, new ARRAY( des, con, models ) );
            st.setArray( 3, new ARRAY( des, con, types ) );
            st.registerOutParameter( 4, OracleTypes.CURSOR );
            st.execute();
            ResultSet cursor = ((OracleCallableStatement)st).getCursor(4);

            while ( cursor.next() )
            {
                int id = cursor.getInt(1);
                String product = cursor.getString(2);
                String model   = cursor.getString(3);
                String type    = cursor.getString(4);

                System.out.println( String.format( "Id: %5d", id ) );
                System.out.println( String.format( "  Product: %s\t", product ) );
                System.out.println( String.format( "  Model:   %s", model ) );
                System.out.println( String.format( "  Type:    %s", type ) );
            }
        } catch(ClassNotFoundException | SQLException e) {
            System.out.println(e);
        }
    }
}