2013-04-30 34 views
0

我在Java中使用了一个字符串SQL查询,我需要有条件地忽略或添加AND子句。例如,假设下面的查询,在Oracle SQL中有条件地添加AND条件

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

所以它的一样,如果名称为空或null我想忽略它,如果计数状态是总我需要执行以下条件t.status =“取消”和t.status ='确认'。像下面的伪查询,但我想我只能使用存储过程中的条件不正常的字符串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 = ? 
} 
+0

相关:http://stackoverflow.com/a/15122018/1065197。这个例子在MySQL上,但也适用于任何其他的RDBMS。 – 2013-04-30 04:15:46

回答

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) 

FOR YOU例

WHERE t.status = CASE WHEN t.status = 'Total' THEN 'Total' ELSE :param END 
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') 
)