Friday, April 29, 2011

Using SQL IN clause with Prepared Statement

Using IN clause in prepared statements is not straight forward fortunately, there is a hack available for this scenario.

Example: Get list of customers who are in east cost states.
SQL could be: SELECT * FROM CUSTOMERS WHERE CUST_STATUS='ACTIVE' AND STATE IN('NJ','NY','MA','NH')

prepared statement - "SELECT * FROM  CUSTOMERS WHERE CUST_STATUS=? AND STATE IN (LIST_STATES)"

List queryForList = jdbcTemplate.queryForList(
    StringUtils.replace(sqlString, "LIST_STATES",
    ("'"+ StringUtils.replace(functions,",", "','") + "'")),new Object[] {});

No comments:

Post a Comment