Re: PreparedStatement + "order by ?"



"Chris" <krystofffff@xxxxxxxxx> wrote in message
news:1140182918.954098.131260@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi

Is there a way to use a PreparedStatement with a query such as
"SELECT * FROM table ORDER BY ?;"
where the first parameter is the name of the table field I'd like to
order the results to ?

Statement parameters can be used to substitute for constant expressions, not
metadata objects by name. You can't do the above, and for similar reasons
you can't do things like "SELECT * FROM ?". As Joe Weinstein points out,
the query optimizer can't decide which indexes to use.

I tried to following code :

PreparedStatement p = new PreparedStatement("SELECT * FROM table ORDER BY
?");
p.setString(1,"name");

The query seems to properly compile and execute, but the ResultSet is
not ordered as it should be :(

You've substituted the string "name" as a constant string expression, not
the name of a field. So it's as if you had used ORDER BY 'name' instead of
ORDER BY name. Ordering by a constant value is not an error, but it does
mean that every row will tie with every other row in the sorting. Therefore
the order in which the rows are returned is arbitrary.

Regards,
Bill K.


.



Relevant Pages

  • Re: A Really Clever Way of Doing DB Access - Can It be Done in Java 5?
    ... > public User getUserByName. ... first argument binds to first parameter in the ... String query(); ... public ListallUsers(); ...
    (comp.lang.java.programmer)
  • Re: Parameter Query
    ... I think the first parameter should be served on a form in a combo box ... this query and execute it from there. ... Tom Ellison ... Microsoft Access MVP ...
    (microsoft.public.access.queries)
  • Re: How do I get parameters printed on report when query not attached
    ... Include the parameters as calculated fields in the query, ... SELECT T.*, [First Parameter] AS FPar, ... query and I need to print those parameters on the sixth report query. ...
    (microsoft.public.access.reports)
  • Re: Expressions for parameters in query
    ... Field: LessThan4: Len> 4 ... True) only Fund with len <= 4 are returned ... I have created a form to pass parameters to a query. ... The first parameter ...
    (microsoft.public.access.queries)
  • Re: Macro that querys only the most current dBase file.
    ... One way is the substitute the file reference in the select ... Dim fname as String ... > I am using Excell 2000 to query an external dBase file. ... > I sucessfully recorded a Macro that follows my MS Query ...
    (microsoft.public.excel.programming)