实现一个按函数值递增的序列

Implement a sequence that increments by value of a function

我想创建一个简单的序列:

 CREATE SEQUENCE supplier_seq
   MINVALUE 1
  START WITH 3
  INCREMENT BY  4
  CACHE 20000;

但是,我想使用由 java 端实现的某些因素确定的函数对增量值进行半随机化。

我想测试这个的第一步可能是这样的:

   CREATE SEQUENCE supplier_seq
       MINVALUE 1
      START WITH 3
     INCREMENT BY  myfunction
      CACHE 20000;

我试过这个:

     CREATE SEQUENCE supplier_seq
        MINVALUE 1
      START WITH 3
        INCREMENT BY  (declare 
   rtrnt number;
  begin 
      rtrnt :=semiRandomize();
   end; 
    )
     CACHE 20000;

我意识到这很荒谬..但必须有某种方法可以做这样的事情。任何指针?

这个怎么样?不是真正的 序列 ,但是 - 可能适合您的需要。它是一个选择一个随机数并将其存储到带有主键的 table 中的函数。如果该号码已被使用,则会被跳过。该函数检查是否所有数字都已被使用;如果是这样,它会引发错误。

在这个例子中,我创建了一个 5-numbers "sequence"(所以它很快就会失败)。

Table & 函数:

SQL> create table t_seq (supseq  number constraint pk_tseq primary key);

Table created.

SQL> create or replace function f_supseq
  2    return number
  3  as
  4    l_range  number := 5; -- number of values in a "sequence"
  5    l_seq    number;      -- a new "sequence" number
  6    l_cnt    number;      -- number of used numbers
  7    pragma autonomous_transaction;
  8  begin
  9    select count(*) into l_cnt from t_seq;
 10    if l_cnt < l_range then
 11       -- there are still some available numbers so - let's get them
 12
 13       -- don't let anyone mess with the table
 14       lock table t_seq in exclusive mode;
 15       while l_seq is null loop
 16         begin
 17           insert into t_seq (supseq) values
 18             (round(dbms_random.value(1, l_range)))
 19             returning supseq into l_seq;
 20         exception
 21           when dup_val_on_index then
 22             -- that number has already been used; skip it
 23             null;
 24         end;
 25       end loop;
 26       commit;
 27    else
 28       raise_application_error(-20001, 'No more available numbers');
 29    end if;
 30
 31    return l_seq;
 32  end;
 33  /

Function created.

正在获取随机 "sequence" 值:

SQL> select f_supseq from dual;

  F_SUPSEQ
----------
         2

SQL> select f_supseq from dual;

  F_SUPSEQ
----------
         4

SQL> select f_supseq from dual;

  F_SUPSEQ
----------
         1

SQL> select f_supseq from dual;

  F_SUPSEQ
----------
         3

SQL> select f_supseq from dual;

  F_SUPSEQ
----------
         5

SQL> select f_supseq from dual;
select f_supseq from dual
       *
ERROR at line 1:
ORA-20001: No more available numbers
ORA-06512: at "SCOTT.F_SUPSEQ", line 28

Table内容:

SQL> select * From t_seq;

    SUPSEQ
----------
         1
         2
         3
         4
         5

SQL>