我的batis条件执行查询WHERE子句基于传入的null变量

时间:2014-02-11 21:47:56

标签: java sql spring mybatis

在我的batis中,我有一个查询将用于根据日期进行查询,否则它应该在一个范围之间获得sysdate。有两个可能的可执行where子句,但我只想执行其中一个。

SELECT distinct support_id AS object_id, 2 as app_context_id, 
            0 as domain_cdc_id, 'S' as object_type, 'NEW' as domain_cdc_status, 1 as attribute_group_num, 
            sysdate as created_on FROM fdrdbo.v_facility_support 
            WHERE support_version_valid_from_dt = to_date('${passedInVar}', 'yyyy/mm/dd') 

如果$ {passInVar}为null,那么我希望使用以下WHERE条件!

WHERE SYSDATE BETWEEN support_version_valid_from_dt AND support_version_valid_to_dt

我怎样才能像这样构建它?

2 个答案:

答案 0 :(得分:3)

使用dynamic SQL

SELECT distinct support_id AS object_id, 2 as app_context_id, 
        0 as domain_cdc_id, 'S' as object_type, 'NEW' as domain_cdc_status, 1 as attribute_group_num, 
        sysdate as created_on FROM fdrdbo.v_facility_support 
WHERE
<if test="passedInVar != null">
    support_version_valid_from_dt = to_date('${passedInVar}', 'yyyy/mm/dd') 
</if>
<if test="passedInVar == null">
    SYSDATE BETWEEN support_version_valid_from_dt AND support_version_valid_to_dt
</if>

答案 1 :(得分:1)

你可以加入这两个WHERE:

WHERE
('${passedInVar}' IS NULL AND SYSDATE BETWEEN support_version_valid_from_dt AND support_version_valid_to_dt)
OR
('${passedInVar}' IS NOT NULL AND support_version_valid_from_dt = to_date('${passedInVar}', 'yyyy/mm/dd'))