Creating a sequence for a varchar2 field in Oracle

后端 未结 4 1390
傲寒
傲寒 2021-01-14 00:58

I want to create a sequence for this varchar. It would have been easier had it been a number instead of varchar. In that case, I could do

seq_no := se

4条回答
  •  悲&欢浪女
    2021-01-14 01:53

    If you're able I'd actually use a virtual column as defined in the CREATE TABLE syntax. It makes it more easily extensible should the need arise.

    Here's a working example.

    SQL> create table tmp_test (
      2     id number(7,0) primary key
      3   , col1 number
      4   , seq varchar2(8 char) generated always as (
      5           'A' || to_char(id, 'FM0999999'))
      6      );
    
    Table created.
    
    SQL>
    SQL> create sequence tmp_test_seq;
    
    Sequence created.
    
    SQL>
    SQL> create or replace trigger tmp_test_trigger
      2    before insert on tmp_test
      3    for each row
      4  begin
      5
      6    :new.id := tmp_test_seq.nextval;
      7  end;
      8  /
    
    Trigger created.
    
    SQL> show errors
    No errors.
    SQL>
    SQL> insert into tmp_test (col1)
      2   values(1);
    
    1 row created.
    
    SQL>
    SQL> select * from tmp_test;
    
            ID       COL1 SEQ
    ---------- ---------- --------------------------------
             1          1 A0000001
    

    Having said that; you would be better off if you did not do this unless you have an unbelievably pressing business need. There is little point to making life more difficult for yourself by prepending a constant value onto a number. As A will always be A it doesn't matter whether it's there or not.

提交回复
热议问题