根据SQL查询中传递的参数选择WHERE之后的部分

时间:2019-07-19 08:38:45

标签: java sql postgresql

我需要根据传递的参数替换查询条件以选择记录数

我写了2个查询,但不知道如何在1个查询中组合

如果parent_uid为null,我需要执行:

SELECT count(*) FROM TABLE WHERE 
parent_uid IS null AND name = 
:name AND tenant_uid = :tenant_uid;

其他:

SELECT count(*) FROM TABLE WHERE 
parent_uid = :parent_uid AND name = 
:name AND tenant_uid = :tenant_uid

这是我需要的伪代码

IF parent_uid IS null 
THEN SELECT count(*) FROM TABLE WHERE parent_uid IS null AND name = :name AND tenant_uid = :tenant_uid

ELSE SELECT count(*) FROM TABLE WHERE parent_uid = :parent_uid AND name = :name AND tenant_uid = :tenant_uid END IF;
/**
 * returns the count of categories that contain all parameters passed
 * @param name category name
 * @parm parentUid parent category uid
 * @param tenantUid tenant uid
 * @return count of records
 */
public int checkCategoryUniqueName(UUID parentUid, String name, UUID tenantUid)
{
    MapSqlParameterSource map = new MapSqlParameterSource()
            .addValue(PARENT_UID_PARAMETER, parentUid)
            .addValue(NAME_PARAMETER, name)
            .addValue(TENANT_UID_PARAMETER, tenantUid);

    return jdbcTemplate.queryForObject(GET_ECATEGORY_COUNT, map , Integer.class);
}

2 个答案:

答案 0 :(得分:1)

不需要ifs。

WHERE (:parent_uid IS NULL AND parent_uid IS NULL) OR (parent_uid=:parent_uid)

答案 1 :(得分:0)

您最好用您的语言(我想是Java)构造适当的SQL字符串。

String sqlParentUid = " parent_uid IS null "
if (parentUid != null) { // parentUid from function
    sqlParentUid = " parent_uid = " + parentUid.toString()
}

然后将这部分添加到基本sql并运行查询