有条件地在Oracle SQL中添加AND条件

时间:2013-04-30 04:12:12

标签: java sql oracle

我在Java中使用String SQL查询,我需要有条件地忽略或添加AND子句。例如,假设以下查询,

select t.name from test t where
t.id=?
and
t.name=?
and
t.status=?

所以如果name为空或null我想忽略它,如果计数状态是total我需要在条件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 = ?
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这样的东西
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')
)