在min_value和max_value oracle之间生成数字

时间:2016-05-09 11:13:43

标签: sql oracle performance

我有两种方法可以解决,但两种方法的效率都很低,无法使用10 8 以上的值。

方法1

 select 100 + rownum - 1 from dual connect by level <= (200 - 100 + 1)

方法2

select rownum + 100 - 1
from (select 1 from dual group by cube(1, 2, 3, 4, 5, 6, 7, 8, 9))
where rownum < (200 - 100 + 1)

但第一种方法在最大值为100,000,000时失败,第二种方法需要大量时间来处理。

请建议一种有效的方法, 我能想到序列,但我想时间成本会更高。

更新

第一种方法中的

错误

  

ORA-30009:没有足够的内存用于CONNECT BY操作

3 个答案:

答案 0 :(得分:8)

对于那么多行,流水线函数可能是最好的解决方案:

staffA

简单:

create or replace TYPE t_numbers IS TABLE OF NUMBER;
/

create or replace function generate_series(p_min integer, p_max integer)
  return t_numbers pipelined
as  
begin
  for i in p_min..p_max loop
    pipe row (i);
  end loop;
end;
/

我的笔记本电脑大约需要30秒

答案 1 :(得分:2)

其他一些选择:

选项1 - 生成集合

CREATE TYPE intlist IS TABLE OF NUMBER(10,0);
/

CREATE FUNCTION list_between(
  min_value NUMBER,
  max_value NUMBER
) RETURN intlist DETERMINISTIC
AS
  o_lst intlist := intlist();
BEGIN
  IF ( min_value <= max_value ) THEN
    o_lst.EXTEND( max_value - min_value + 1 );
    FOR i IN 0 .. max_value - min_value LOOP
      o_lst( i ) := i + min_value;
    END LOOP;
  END IF;
  RETURN o_lst;
END;
/

SELECT COLUMN_VALUE
FROM   TABLE( list_between( 123456789, 987654321 ) );

选项2 - 使用递归子查询分解子句

WITH sqfc ( min_value, max_value ) AS (
  SELECT 123456789, 987654321 FROM DUAL
  UNION ALL
  SELECT min_value + 1, max_value
  FROM   sqfc
  WHERE  min_value < max_value
)
SELECT min_value AS value
FROM   sqfc;

选项3 - 使用流水线功能

CREATE FUNCTION pipelined_list_between (
  min_value NUMBER,
  max_value NUMBER
) RETURN intlist DETERMINISTIC PIPELINED
AS
BEGIN
  FOR i IN min_value .. max_value LOOP
    PIPE ROW ( i );
  END LOOP;
END;
/

SELECT COLUMN_VALUE
FROM   TABLE( pipelined_list_between( 123456789, 987654321 ) );

答案 2 :(得分:0)

第一种方法的变化。

select  rownum + min_val
    from (
               select rownum rn
               from
                       (select rownum rn from dual connect by level <= 1000) t1,
                       (select rownum rn from dual connect by level <= 1000) t2,
                       (select rownum rn from dual connect by level <= 1000) t3
               where rownum <= max_val- min_val +1
       )