2

我进退两难,我正在使用 Java 和 Oracle,并试图在 PL/SQL 端保留查询。一切都很好,直到我有这些可能有条件也可能没有条件的复杂查询。

在 Java 中将WHERE子句与条件放在一起并不难,但这并不好。在 PL/SQL 方面,我还发现唯一的可能性dynamic queries是字符串操作,例如

IF inputname IS NOT NULL THEN    
    query := query ||' and NAME=' || inputname; 
END IF;

现在我在想,我将在 PL/SQL 中留下查询并发送WHERE带有函数参数的子句。请问有什么好的建议或例子吗?

4

5 回答 5

1

SQLBuilder在 Java 方面可能对您有用。它允许您编写动态构建 sql 的编译时检查 Java 代码:

String selectQuery =
  (new SelectQuery())
  .addColumns(t1Col1, t1Col2, t2Col1)
  .addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)
  .addOrderings(t1Col1)
  .validate().toString();
于 2008-09-23T18:18:23.947 回答
1

正如您所发现的,PL/SQL 不适合创建动态 SQL,它的字符串操作很痛苦。您可以从客户端发送 where 子句,但您必须确保检查 SQL 注入,即确保该短语以“where”开头,没有分号或仅在末尾(如果它可能出现在中间您需要从字符串分隔符中查看,并且只允许在其中使用)等。另一个选项是一个存储过程,它采用字段过滤器的预定义参数列表,对参数字段应用每列的“喜欢”。

于 2008-09-23T18:25:16.270 回答
0

I think its better to have the whole logic of the query creation in one place, Java or Oracle. I asume that you know how to do it in Java. In Oracle if the query only retrieves a row you can use the EXECUTE IMMEDIATE ... INTO clause.

If the query return multiple rows and has single parameters (no use the IN operator ) you can use the REF CURSOR strategy to loop the query results or return the cursor itself to the Java program (you must import Oracle java clases if you use it). First Ref Cursor answer in Google

If you must use the IN parameter ( or in another rare cases) you must parse the query with the DBMS_SQL package, which is TOO verbose and a little tricky to use, but it's VERY flexible. DBMS_SQL doc (watch the flow diagram BEFORE read the methods)

于 2008-09-23T19:12:58.950 回答
0

在 PL/SQL 中使用:

EXECUTE IMMEDIATE lString;

这使您可以将 lString(一个 VARCHAR2)构建到您想要使用的大部分 SQL 中。例如

  EXECUTE IMMEDIATE 'SELECT  value
                     FROM    TABLE
                     WHERE   '||pWhereClause
  INTO    lValue;

您还可以在 EXECUTE IMMEDIATE 中返回多行并执行 DDL 语句。

于 2008-09-23T18:21:38.870 回答
0

是的,EXECUTE IMMEDIATE 也是我的朋友。感谢您的建议。我想这次我尝试只发送带参数的 WHERE 子句

于 2008-09-23T18:55:29.880 回答