日期:2014-05-16  浏览次数:20472 次

Oracle数据库中IN参数个数超过1000的问题

业务问题:

?在oracle中,我们使用in方法查询记录的时候,如果in后面的参数个数超过1000个,那么会发生错误,JDBC会抛出“java.sql.SQLException: ORA-01795: 列表中的最大表达式数为 1000”这个异常。

?

解决方案:

这个问题的思想是把参数列表分段,将SQL语句拼成如下形式:

select * from spp_info where keyword in (a,b,c) union select * from spp_info where keyword in (d,e,f)

public class Test {
	public static void main(String[] args) {
		String sql = "select * from spp_info where keyword";
		String keyword = "a,b,c,d,e,f";
		int splitNum = 3;
		System.out.println(setWhereInArray(sql, keyword, splitNum));
	}

	/**
	 * More than 1000 divided into multiple sql queries
	 * 
	 * @param orgSql
	 * @param paramValue
	 * @param splitNum query number
	 * @return sql
	 */
	public static String setWhereInArray(String orgSql, String paramValue, int splitNum) {
		String paramArray[] = paramValue.split(",");
		int inArrayNum = paramArray.length % splitNum == 0 ? paramArray.length / splitNum : paramArray.length / splitNum + 1;

		int m = 0;
		int b = 0;
		int n = splitNum;
		String p[] = new String[inArrayNum];
		String sql[] = new String[inArrayNum];

		for (int k = 0; k < paramArray.length; k++) {
			if (b < inArrayNum) {
				p[b] = "";
				for (; m < n; m++) {
					if (m >= paramArray.length) {
						break;
					}
					p[b] += paramArray[m] + ",";
				}
				p[b] = p[b].substring(0, p[b].lastIndexOf(","));
				sql[b] = orgSql + " in (" + p[b] + ")";
				b++;
				n += splitNum;
			}
		}
		String newSql = "";
		for (int q = 0; q < sql.length; q++) {
			newSql += sql[q] + " union ";
		}
		newSql = newSql.substring(0, newSql.lastIndexOf(" union "));
		return newSql;
	}
}

?

?

1 楼 capp0139 2013-11-04  
截取1000个in 条件中间用 or 就行了,不需要union
2 楼 icefishc 2013-11-04  
这么多东西你就不该用in了
3 楼 houyujiangjun 2013-11-04  
也就是oracle 让你这么瞎搞,你用用mysql,百万计,十个以上的in 不跑个几分钟出来才怪。。。。
4 楼 logqq 2013-11-05  
LZ 霸气啊 。。IN 后面的参数能用到这么多?
5 楼 zhangjim 2013-11-09  
没办法啊,in里面的关键词是随机个数的