问题
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