SQL条件语句 [英] SQL conditional statement
本文介绍了SQL条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在ORACLE sql代码中创建条件语句
我在java中有一个带有2个参数的函数。
getchildren(child1,child2) ..此函数的参数用于创建查询语句
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;
}
这显然是伪代码。
我需要帮助为 where 子句创建条件执行,以便在条件有效时执行每个where子句。我尝试过类似于我的东西,但没有运气。
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.
推荐答案
使用StringBuilder动态构建查询。
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());
这篇关于SQL条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文