Re: PreparedStatement + "order by ?"





Chris wrote:

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 ?

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 :(

Moreover, I'd like to do something like :

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

But I think it is really impossible this time ...

Any Idea ?

Hi. This will be impossible for any commercial quality DBMS and driver.
The reason is that those will want to be able to precompile the SQL
and store a query plan in the DBMS to reuse. *Value* markers can
be filled in later, but the DBMS can't make a plan that doesn't know
what columns it will be even looking for or ordering by until later.
That would change the plan completely each time. Eg:
(1 - order by <primary key> will use existing unique index)
(2 - order by <non-indexed field> will have to fill a temp table and sort)

HTH,
Joe Weinstein at BEA Systems

.



Relevant Pages

  • Re: Why is this
    ... would be to have a single index on (lastrecon, acctnum, deposit) [or ... cover the query and handle the restrictive condition immediately. ... there is no perfect query plan. ... use the index for TOP 1, even if it used quite a few bookmark lookups, ...
    (microsoft.public.sqlserver.server)
  • Re: Query optimizer issue
    ... Consider a stored proc defined as follows: ... when compiling a plan. ... parameter @p1 into the query at compile time before a plan for the query ... execution plans, but a key requirement for everything to work as expected ...
    (microsoft.public.sqlserver.server)
  • Re: Execute SQL UD Function call timeout, 1-3 seconds in query ana
    ... We did build a little ASP.NET page yesterday that lets us put a given sql ... query into a text box and then return the execution plan (using Showplan_Text ... Query Analyzer. ...
    (microsoft.public.dotnet.framework.adonet)
  • Re: Store procedure vs Direct statement ???
    ... Try opening up query analyzer and checking out the query plan or ... advantages of using stored procedures over not using stored procedures is the ... the better the overall performance of your SQL ... dynamic sql versus the execution plan for a stored procedure. ...
    (microsoft.public.dotnet.framework.adonet)
  • Re: SP runs slower than same query in Query analyzer. Why??
    ... Andrew your reply was useful but I'm quite new to sql server and I'm ... query gives me the results in 3-4 seconds. ... > Keep in mind that the server has to compile a complete execution plan ... > when compiling a plan. ...
    (microsoft.public.sqlserver.clients)