SQL conditional statement

耗尽温柔 提交于 2020-01-15 06:56:25

问题


I'm trying to create a conditional statement in an ORACLE sql code I have a function in java that takes 2 parameters. getchildren(child1,child2)..this function's parameters are used to create a query statement

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;


}

This is obviously pseudocode. I need help creating a conditional execution for the where clauses so that each "where" clause is executed when its condition is valid. I've tried something similar to what I have up there but with no luck.


回答1:


Use a StringBuilder to dynamically build your query.

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());



回答2:


Build up the query using a StringBuilder piece by piece. Start by appending "select * from table1 where ". Then write your if statements in plain Java, and in each block just append the appropriate clause.



来源:https://stackoverflow.com/questions/7097945/sql-conditional-statement

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