How to create an Oracle sequence starting with max value from a table?

后端 未结 8 1282
[愿得一人]
[愿得一人] 2020-12-02 20:14

Trying to create a sequence in Oracle that starts with the max value from a specific table. Why does this not work?

CREATE SEQUENCE transaction_sequence
  MI         


        
8条回答
  •  抹茶落季
    2020-12-02 20:25

    you might want to start with max(trans_seq_no) + 1.

    watch:

    SQL> create table my_numbers(my_number number not null primary key);
    
    Table created.
    
    SQL> insert into my_numbers(select rownum from user_objects);
    
    260 rows created.
    
    SQL> select max(my_number) from my_numbers;
    
    MAX(MY_NUMBER)
    --------------
               260
    
    SQL> create sequence my_number_sn start with 260;
    
    Sequence created.
    
    SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
    insert into my_numbers(my_number) values (my_number_sn.NEXTVAL)
    *
    ERROR at line 1:
    ORA-00001: unique constraint (NEIL.SYS_C00102439) violated
    

    When you create a sequence with a number, you have to remember that the first time you select against the sequence, Oracle will return the initial value that you assigned it.

    SQL> drop sequence my_number_sn;
    
    Sequence dropped.
    
    SQL> create sequence my_number_sn start with 261;
    
    Sequence created.
    
    SQL>  insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
    
    1 row created.
    

    If you're trying to do the 'gapless' thing, I strongly advise you to

    1 not do it, and #2 not use a sequence for it.

提交回复
热议问题