【问题标题】:Conditionally add AND conditions in Oracle SQL在 Oracle SQL 中有条件地添加 AND 条件
【发布时间】: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 = ?
}

【问题讨论】:

标签: java sql oracle


【解决方案1】:

怎么样

select t.name from test t where
t.id=?
and
(t.name=? OR t.name IS NULL)
and
(
        (t.status=? AND t.statuc <> 'total')
    OR  (t.status = 'total')
)

【讨论】:

    【解决方案2】:
    May be try this technice
    
    (:param IS NULL OR <someField> = (other condition) :param)
    
    You query looks like
    
    SELECT ... FROM ...
    WHERE
    (:param IS NULL OR <someField> = (other condition) :param)
    AND
    (:param1 IS NULL OR <someField> = (other condition) :param1)
    

    给你的例子

    WHERE t.status = CASE WHEN t.status = 'Total' THEN 'Total' ELSE :param END
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多