我在APEX
中有一个查询,该查询基于顶点中项目的值使用where子句条件。如果日期是null
,那么我想显示表中的所有记录,如果日期不是null
,我想基于该值添加where条件。我怎样才能做到这一点 ?
如果P2_SELECT_DATE
不为null,我想添加以下两个条件:
select * from HR_DATA
where
:P2_SELECT_DATE between person_eff_start_date and person_eff_end_date
and :P2_SELECT_DATE between nvl(assign_eff_start_date,sysdate-1) and nvl(assign_eff_end_date, sysdate+1)
如果P2_SELECT_DATE
为null,那么我根本就不想在where子句中拥有这些条件。
答案 0 :(得分:2)
您可以这样做:
select * from HR_DATA
where (:P2_SELECT_DATE is null
or (:P2_SELECT_DATE between person_eff_start_date and person_eff_end_date
and :P2_SELECT_DATE between nvl(assign_eff_start_date,sysdate-1)
and nvl(assign_eff_end_date, sysdate+1)
)
有时候,如果有很多可选的过滤器,动态创建查询会更有效:
declare
q long;
begin
q := 'select * from HR_DATA where 1=1';
if :P2_SELECT_DATE is null then
q := q || ' and :P2_SELECT_DATE between person_eff_start_date and person_eff_end_date'
|| ' and :P2_SELECT_DATE between nvl(assign_eff_start_date,sysdate-1)'
|| ' and nvl(assign_eff_end_date, sysdate+1);
end if;
return q;
end;
“其中1 = 1”只是一个技巧,因此任何有条件附加的过滤器总是以“和”开头。