0

我在 Java 中使用 String 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 = ?
}
4

2 回答 2

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
于 2013-04-30T04:15:45.340 回答
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')
)
于 2013-04-30T04:16:37.660 回答