Home  >  Article  >  Database  >  Oracle教程:ORA-01795的原因及解决办法

Oracle教程:ORA-01795的原因及解决办法

WBOY
WBOYOriginal
2016-06-07 17:11:561581browse

找出抛异常时执行的SQL语句,貌不惊人啊,很平常一SQL语句,内容类似:SELECT * FROM DUAL T WHERE T.DUMMY IN (

系统报出一SQL异常,内容如下:

java.sql.SQLException: ORA-01795: maximum number of expressions in a list is 1000

找出抛异常时执行的SQL语句,貌不惊人啊,很平常一SQL语句,内容类似:SELECT * FROM DUAL T WHERE T.DUMMY IN ('1', '2', '3', ...),只是IN后括号里的主键值多了些,其它没啥特别的。

看ORA-01795中给出的内容是SQL语句的 expressions 中list接受的最大值是1000,查了下ORA-01795的说明,确定问题出在IN后括号里的主键值超过1000上。

解决思路大至有两种,一种是换用JOIN或者EXIST,另一种是仍然用IN,但是把条件分成多个少于1000的IN即:SELECT * FROM DUAL T WHERE T.DUMMY IN ('1', '2', '3',...,'1000') OR IN ('1001', '1002', ..., '2000') OR ...

由于个人感觉JOIN不直观、EXIST含义不易理解,,采用了方式二,附代码:

2011-2-14 15:56:17,对代码进行了修正,感谢gouliming及时指出代码中的错误。

========================================================


StringBuffer sb = new StringBuffer();

int inNum = 1; //已拼装IN条件数量
for(int i=0; i

    if(StringUtil.isEmpty(custNOs[i])) continue;
   
    //这里不要犯低级错误而写成:if(i == custNOs.length)
    if(i == (custNOs.length-1))
        sb.append("'" + custNOs[i] + "'");    //SQL拼装,最后一条不加“,”。
    else if(inNum==1000 && i>0) {
        sb.append("'" + custNOs[i] + "' ) OR CUST_NO IN ( ");    //解决ORA-01795问题
        inNum = 1;
    }
    else {
        sb.append("'" + custNOs[i] + "', ");
        inNum++;
    }

}

String selectSQL = "SELECT * FROM CUSTOMER T WHERE T.CUST_NO IN ( " + sb.toString() + " )";

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn