0

我正在寻找创建一个简单的序列:

 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;

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

4

1 回答 1

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>
于 2019-03-03T19:36:54.133 回答