【问题标题】:SQL conditional statementSQL 条件语句
【发布时间】:2011-10-29 04:52:07
【问题描述】:

我正在尝试在 ORACLE sql 代码中创建条件语句 我在java中有一个带有2个参数的函数。 getchildren(child1,child2)..该函数的参数用于创建查询语句

public ResultSet getchildren(String Child1, String child2) throws SQLException 
{

 stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
 ResultSet.CONCUR_READ_ONLY);


     query ="select * from table1 

            if child1 is not null and child2 is null
            { where child1 = 1 }
            else if child2 is not null AND child1 is null
            {where child2 = 2}
            else
             {//some other where statment } 
            ";



    System.out.println("\nExecuting query: " + query);
    rset = stmt.executeQuery(query);

    return rset;


}

这显然是伪代码。 我需要帮助为 where 子句创建条件执行,以便每个 "where" 子句在其条件有效时执行。我已经尝试过类似于我在那里的东西,但没有运气。

【问题讨论】:

    标签: java sql oracle if-statement conditional


    【解决方案1】:

    使用StringBuilder 逐个构建查询。首先附加"select * from table1 where "。然后用纯 Java 编写你的 if 语句,并在每个块中添加适当的子句。

    【讨论】:

      【解决方案2】:

      使用 StringBuilder 动态构建您的查询。

      StringBuilder queryBuilder = new StringBuilder();
      queryBuilder.append("select * from table1 ");
      
      if ( child1 != null && child2 == null) 
         queryBuilder.append(" where child1 = 1 ");
      else if ( child2 != null && child1 == null)
         queryBuilder.append(" where child2 = 1 ");
      else
         queryBuilder.append(" where bla ");
      
      // Execute queryBuilder.toString();
      rset = stmt.executeQuery(queryBuilder.toString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 2014-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多