我有一个问题,我甚至不知道我正在尝试或想要做的事情是否有可能。
我有一个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或者可以有任何值,所以我想要的是忽略那些值为null的参数。
对于Eg: - 对于上述查询,结果应与
相同 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行,我做错了什么。
答案 0 :(得分:1)
喜欢这个
...
and (@value3 is null or col3 = @value3)
and (@value4 is null or col4 = @value4)
....