服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Oracle - Oracle使用in语句不能超过1000问题的解决办法

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

2022-09-14 18:22谢哥哥blog Oracle

最近项目中使用到了Oracle中where语句中的in条件查询语句,在使用中发现了问题,所以下面这篇文章主要给大家介绍了关于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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
建立临时表之后,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报错的问题了

?
1
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) 也就是元组,语法如下:

?
1
2
3
4
5
6
7
8
9
SELECT * FROM TABLE_NAME WHERE (1, COLUMN_NAME) IN
((1, VALUE_1),
(1, VALUE_2),
...
...
...
...
(1, VALUE_1000),
(1, VALUE_1001));

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

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

上面的语句其实等同于:

?
1
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 原来是这写:

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

现在改成:

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

总结

到此这篇关于Oracle使用in语句不能超过1000问题解决的文章就介绍到这了,更多相关Oracle in语句不能超过1000内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_42825651/article/details/123045574

延伸 · 阅读

精彩推荐