【发布时间】:2013-04-30 12:21:23
【问题描述】:
我在 Java 中使用字符串 SQL 查询,我需要有条件地忽略或添加 AND 子句。例如假设下面的查询,
select t.name from test t where
t.id=?
and
t.name=?
and
t.status=?
因此,如果名称为空或为空,我想忽略它,如果计数状态为总计,我需要在条件 t.status= 'cancel' 和 t.status = 'confirm' 下执行。就像下面的伪查询一样,但我想我只能在存储过程中使用条件,而不是在普通字符串 sql 中?
select t.name from test t where
t.id=?
and
if(t.name != null){
t.name=?
}
and
if(t.status.equals = 'total'){
t.status='total'
}else{
t.status = ?
}
【问题讨论】:
-
相关:stackoverflow.com/a/15122018/1065197。该示例适用于 MySQL,但也适用于任何其他 RDBMS。