Oracle, SELECT IN and PreparedStatement.setArray
843854Mar 19 2004 — edited Apr 22 2004I want to execute the following query: SELECT * FROM SOMETABLE WHERE IDFIELD IN (?)
The number of values in the IN list is variable. How can I do this with a prepared statement?
I am aware of the different alternatives:
1) Keep a cache of prepared statement for each sized list seen so far.
2) Keep a cache of prepared statements for different sizes (1, 5, 10, 20) and fill in the left over parameter positions with the copies first value.
They both have the disadvantage that there could be many prepared statements for each query that get used once, and never used again.
I have tried this:
stmt.execute ("CREATE OR REPLACE TYPE LONGINTLIST AS TABLE OF NUMBER(15)");
ArrayDescriptor desc = ArrayDescriptor.createDescriptor ("LONGINTLIST", conn);
long idValues [] = {2, 3, 4};
oracle.sql.ARRAY paramArray = new oracle.sql.ARRAY (desc, conn, idValues);
PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (?)");
query.setArray (1, paramArray);
But Oracle gives a data conversion error.
I then tried this:
PreparedStatement query = conn.prepareStatement ("SELECT * FROM MYTABLE WHERE ID_FIELD IN (SELECT * FROM TABLE (?))");
This works and the rows are returned, but the Oracle optimizer does not like it very much, since it always does a full table scan even though there is a primary key index on ID_FIELD.
Any ideas?
I also tried this:
OraclePreparedStatement oraQuery = (OraclePreparedStatement) query;
oraQuery.setARRAY (1, paramArray);
But same behavior.
Roger Hernandez