今天遇到这么个小问题,说来也常见。就记录一下。

 

查询 一个输入范围 内的 数据: Select * from table1 Where fld1>=A and fld<=B

 

其中A,B均为可选输入项目,有如下几种组合:

 

1:A有值,B无值,即 Select * from table1 Where fld1>=A

2:A有值,B有值,即 Select * from table1 Where fld1>=A and fld<=B

3:A无值,B无值,即 Select * from table1 

4:A无值,B有值,即 Select * from table1 Where  fld<=B

 

基本语法如下(Oracle),其中fld1字段为数值型函数

 

 

Select * from table1

Where 

decode('&1','',1,fld1)>=to_number(decode('&1','',1,'&1'))

and

decode('&2','',1,fld1)<=to_number(decode('&2','',1,'&2'))

 

 

基本思路是:

如果输入的值为空,则主动给一个1,将比对字段也设为1。
这样当值为空时,这个条件转化为1>=1,恒定为true,从而使该条件失效(说有效也可以)。

 

同理,如果只是对于一个可选参数,就是

 

Select * from table1

Where 

decode('&1','',1,fld1)>=to_number(decode('&1','',1,'&1'))