解码功能

时间:2013-08-01 20:47:50

标签: sql oracle decode

我的查询有三个提示;部门,从日期和到目的。必须选择部门ID,但可以选择日期范围。如何使日期范围可选?我正在考虑使用解码功能,但不知道如何编写它,以便两个日期提示可以留空。

2 个答案:

答案 0 :(得分:0)

如果您使用的是存储过程,则可以在select语句中执行以下操作:

select *
from table
where (field > inDateStart and field < inDateEnd) or 
      (inDateStart is null and inDateEnd is null)

或使用合并

select *
from table
where (field => coalesce(inDateStart,field) and 
       field <= coalesce(inDateEnd,field) 

这实际上取决于你的具体情况。有些查询适用于第一部分到第二部分。

答案 1 :(得分:0)

假设未指定日期输入为NULL,您可以执行以下小技巧:

with
 TheTable as
 (select 1 dept, sysdate dt from dual
 union
 select 2 dept, sysdate-63 dt from dual
 union
 select 3 dept, sysdate-95 dt from dual
 )
select * 
from thetable
where coalesce(:DateFrom,dt) <= dt
and  coalesce(:DateTo,dt) >= dt
;

需要更多关于数据性质的信息,将dept视为输入...表格是否存储了每个部门的多个日期?

相关问题