Oracle trigger to create an autonumber

前端 未结 2 1321
时光说笑
时光说笑 2021-02-05 20:44

I have never created a trigger in Oracle before so I am looking for some direction.

I would like to create a trigger that increments an ID by one if the ID isnt in the i

相关标签:
2条回答
  • 2021-02-05 21:00

    I would recommend to code this trigger with a condition on the trigger itself, not in the sql block.

    CREATE OR REPLACE TRIGGER your_trigger
    BEFORE INSERT ON your_table
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    WHEN (new.id IS NULL)
      BEGIN
        SELECT your_sequence.nextval
        INTO :new.id
        FROM dual;
      END;
    /
    

    With this solution the trigger is only executed if the condition matches (id is null).

    Otherwise the trigger is always executed and the block checks if id is null. The DB must execute the SQL block which does nothing on not null values.

    0 讨论(0)
  • 2021-02-05 21:19

    Something like this will work on 11g

    CREATE SEQUENCE t1_id_seq 
      start with 10000 
      increment by 1;
    
    CREATE TRIGGER trigger_name
      BEFORE INSERT ON t1
      FOR EACH ROW
    DECLARE
    BEGIN
      IF( :new.id IS NULL )
      THEN
        :new.id := t1_id_seq.nextval;
      END IF;
    END;
    

    If you're on an earlier version, you'll need to do a SELECT INTO to get the next value from the sequence

    CREATE TRIGGER trigger_name
      BEFORE INSERT ON t1
      FOR EACH ROW
    DECLARE
    BEGIN
      IF( :new.id IS NULL )
      THEN
        SELECT t1_id_seq.nextval
          INTO :new.id
          FROM dual;
      END IF;
    END;
    

    Be aware that Oracle sequences are not gap-free. So it is entirely possible that particular values will be skipped for a variety of reasons. Your first insert may have an ID of 10000 and the second may have an ID of 10020 if it's done minutes, hours, or days later.

    Additionally, be aware that Oracle does not support specifying multiple rows in the VALUES clause as MySQL does. So rather than

    insert into t1 (firstname, lastname) values ('Michael','Jordan'),('Larry','Bird')
    

    you'd need two separate INSERT statements

    insert into t1 (firstname, lastname) values ('Michael','Jordan');
    insert into t1 (firstname, lastname) values ('Larry','Bird');
    
    0 讨论(0)
提交回复
热议问题