Oracle使用in语句不能超过1000问题的解决办法

 

前言

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

 

我的解决方案是:

一、建立临时表

ORACLE临时表有两种类型:会话级的临时表和事务级的临时表。

1、ON COMMIT DELETE ROWS

它是临时表的默认参数,表示临时表中的数据仅在事务过程(Transaction)中有效,当事务提交(COMMIT)后,临时表的暂时段将被自动截断(TRUNCATE),但是临时表的结构 以及元数据还存储在用户的数据字典中。如果临时表完成它的使命后,最好删除临时表,否则数据库会残留很多临时表的表结构和元数据。

2、ON COMMIT PRESERVE ROWS

它表示临时表的内容可以跨事务而存在,不过,当该会话结束时,临时表的暂时段将随着会话的结束而被丢弃,临时表中的数据自然也就随之丢弃。但是临时表的结构以及元数据还存储在用户的数据字典中。如果临时表完成它的使命后,最好删除临时表,否则数据库会残留很多临时表的表结构和元数据。

建立临时表之后,in语句里面就可以使用子查询,这样就不会有超过1000报错的问题了create global temporary table test_table 
(id varchar2(50), name varchar2(10)) 
on commit preserve rows; --创建临时表(当前会话生效)

--添加数据
insert into test_table VALUES('ID001', 'xgg');
insert into test_table VALUES('ID002', 'xgg2');

select * from test_table; --查询数据

TRUNCATE TABLE test_table; --清空临时表数据
DROP TABLE test_table; --删除临时表

建立临时表之后,in语句里面就可以使用子查询,这样就不会有超过1000报错的问题了

select * from table_name where id in(select id from test_table);

二、使用in() or in()

官方说: A comma-delimited list of expressions can contain no more than 1000 expressions. A comma-delimited list of sets of expressions can contain any number of sets, but each set can contain no more than 1000 expressions
这里使用oracle tuple( A comma-delimited list of sets of expressions) 也就是元组,语法如下:

SELECT * FROM TABLE_NAME WHERE (1, COLUMN_NAME) IN 
((1, VALUE_1), 
(1, VALUE_2), 
...
...
...
...
(1, VALUE_1000),
(1, VALUE_1001));

比如我们想要从用户表里通过用户id 查询用户信息可以这样写:

select * from user u where (1, u.id) in ((1, 'id001'),(1,'id002'),(1,'id003'))

上面的语句其实等同于:

select * from user u where (1=1 and u.id='id001') or (1=1 and u.id='id002') or (1=1 and u.id='id003')

大家的工程多数会用ORM框架如MyBatis 我们可以借助MyBatis的foreach 原来是这写:

where u.id in
<foreach collection="userIds" item="item" separator="," open="(" close=")" index="">
  #{item}
</foreach>

现在改成:

where (1, u.id) in
<foreach collection="userIds" item="item" separator="," open="(" close=")" index="">
  (1, #{item})
</foreach>

 

总结

关于Oracle使用in语句不能超过1000问题解决的文章就介绍至此,更多相关Oraclein语句不能超过1000内容请搜索编程宝库以前的文章,希望以后支持编程宝库

1、下载地址:https://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/下载解压后可直接打开 ...