2017-06-14 113 views
0

嗯,我有一个问题,我甚至不知道我正在尝试或想要做的事情是否可行。如何忽略SQL查询中的空参数

我有一个SQL查询: -

select * 
from table 
where (col1 >= '2016-07-05' and col2 <= '2016-07-07') 
and col3 = '' 
and col4 = '' 
and col5 = '' 
and col6 = '686486' 
and col7 = '' 
and col8 = ''; 

好吧我使用这个查询来执行搜索操作,我想这是非常特殊的,这就是为什么我在考虑做这种方式的。

所有这些参数可以为空或可以有任何值,所以我只想忽略那些值为null的参数。

对于如: - 对于上述查询的结果应该是一样

select * 
from vehicle 
where (col1 >= '2016-07-05' and col2 <= '2016-07-07') 
and col6 = '686486'; 

编辑1:所有感谢帮助我的第一次,我想什么建议

select * 
from table 
where (('val1' is null or col1 >= 'val1') and ('val2' is null or col2 <= 
    'val2')) 
and ('val3' is null or col3 = 'val3') 
and ('val4' is null or col4 = 'val4') 
and ('val5' is null or col5 = 'val5') 
and ('val6' is null or col6 = 'val6') 
and ('val7' is null or col7 = 'val7') 
and ('val8' is null or col8 = 'val8'); 

但我因为这个查询得到0行,我做错了什么。

回答

1

像这样

... 
and (@value3 is null or col3 = @value3) 
and (@value4 is null or col4 = @value4) 
.... 
+0

我的查询我是否必须写“@”太多,使用简单的SQL,并使用它作为与Java –

+0

@value嵌入SQL我从来没有使用@在sql.Iam只是一个表示查询中的参数。将其替换为搜索字符串。 –

+0

我编辑了问题 –