Is it possible to refer to column names via bind variables in Oracle?

夙愿已清 提交于 2019-11-29 11:25:13

No. You cannot use bind variables for table or column names.

This information is needed to create the execution plan. Without knowing what you want to order by, it would be impossible to figure out what index to use, for example.

Instead of bind variables, you have to directly interpolate the column name into the SQL statement when your program creates it. Assuming that you take precautions against SQL injection, there is no downside to that.

Update: If you really wanted to jump through hoops, you could probably do something like

order by decode(?, 'colA', colA, 'colB', colB)

but that is just silly. And slow. Don't.

As you are using JDBC. You can rewrite your code, to something without bind variables. This way you can also dynamically change the order-by e.g.:

    String query = "SELECT * FROM PERS ";
    if (condition1){
      query = query+ " order by name ";
    // insert more if/else or case statements
    } else {
      query = query+ " order by other_column ";
    }
    Statement select = conn.createStatement();
    ResultSet result = select.executeQuery(query);

Or even

    String columnName = getColumnName(input);
    Statement select = conn.createStatement();
    ResultSet result = select.executeQuery("SELECT * FROM PERS ORDER BY "+columnName);

ResultSet result = select.executeQuery("SELECT * FROM PERS ORDER BY "+columnName);

will always be a NEW statement to the database. That means it is, like Thilo already explained, impossible to "reorder" an already bound, calculated, prepared, parsed statement. When using this result set over and over in your application and the only thing, which changes over time is the order of the presentation, try to order the set in your client code. Otherwise, dynamic SQL is fine, but comes with a huge footprint.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!