Oracle trigger to create an autonumber

前端 未结 2 1322
时光说笑
时光说笑 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.

提交回复
热议问题