处理 Oracle SQL in 超过1000 的解决方案

数据库   发布日期:2025年05月23日   浏览次数:178

    处理oracle sql 语句in子句中(where id in (1, 2, ..., 1000, 1001)),如果子句中超过1000项就会报错。这主要是oracle考虑性能问题做的限制。如果要解决次问题,可以用 where id (1, 2, ..., 1000) or id (1001, ...)

  1. package windy.learn;
  2. import java.util.Collection;
  3. import org.apache.commons.lang3.StringUtils;
  4. public class OracleSqlUtils {
  5. /**
  6. * x,y相除,向上取整
  7. * @param x
  8. * @param y
  9. * @return x,y相除,向上取整
  10. */
  11. private static int ceilDiv(int x, int y) {
  12. int r = x / y;
  13. return r * y == x ? r : r + 1;
  14. }
  15. public static String getOracleSQLIn(Collection<String> ids, String field) {
  16. return getOracleSQLIn(ids, 1000, field);
  17. }
  18. /**
  19. * oracle sql 语句in子句中如果子句中超过1000项就会报错。这主要是oracle考虑性能问题做的限制。 如果要解决次问题,可以用
  20. * where id (1, 2, ..., 1000) or id (1001, ...)
  21. *
  22. * @param ids
  23. * in语句中的集合对象
  24. * @param count
  25. * in语句中出现的条件个数
  26. * @param field
  27. * in语句对应的数据库查询字段
  28. * @return 返回 field in (...) or field in (...) 字符串
  29. */
  30. public static String getOracleSQLIn(Collection<String> ids, int count,
  31. String field) {
  32. String[] idsArr = ids.toArray(new String[0]);
  33. count = Math.min(count, 1000);
  34. int len = idsArr.length;
  35. int size = ceilDiv(len, count);
  36. StringBuilder builder = new StringBuilder();
  37. for (int i = 0; i < size; i++) {
  38. int fromIndex = i * count;
  39. int toIndex = Math.min(fromIndex + count, len);
  40. String productId = StringUtils.defaultIfEmpty(
  41. StringUtils.join(idsArr, "','", fromIndex, toIndex), "");
  42. if (i != 0) {
  43. builder.append(" or ");
  44. }
  45. builder.append(field).append(" in ('").append(productId)
  46. .append("')");
  47. }
  48. return StringUtils.defaultIfEmpty(builder.toString(), field
  49. + " in ('')");
  50. }
  51. }

参考:http://www.cnblogs.com/hoojo/archive/2012/08/31/2665396.html

以上就是处理 Oracle SQL in 超过1000 的解决方案的详细内容,更多关于处理 Oracle SQL in 超过1000 的解决方案的资料请关注九品源码其它相关文章!