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

时间:2019-03-03 05:47:55

标签: oracle plsql sql-function database-sequence

我希望创建一个简单的序列:

 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;

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

1 个答案:

答案 0 :(得分:0)

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

在此示例中,我创建了一个5位数的“序列”(这样它很快就会失败)。

表和功能:

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.

获取随机的“序列”值:

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

表内容:

SQL> select * From t_seq;

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

SQL>