Search code examples
sqloracle11gnetwork-programmingoracle-sqldeveloper

Problem while creating a trigger for automatic generation of primary key values


I'm trying to create a trigger for automatic generation of primary key values using sequences on Oracle SQL Developer.

Since I'm new to this, it sounds kind of vague to me so I tried various things I found online but failed to create what I am supposed to do. I tried this piece of code but I am completely sure that it is wrong.

CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON Orders
FOR EACH ROW
    WHEN (new.ID IS NULL)
BEGIN
    :new.ID := Orders_SEQ.NEXTVAL;
END;

Can someone guide me to what am I supposed to do for this question?


Solution

  • I tried this piece of code but I am completely sure that it is wrong.

    Why? It is completely correct.

    SQL> create table orders (id number);
    
    Table created.
    
    SQL> create sequence orders_seq;
    
    Sequence created.
    
    SQL> CREATE OR REPLACE TRIGGER TRIGGER1
      2  BEFORE INSERT ON Orders
      3  FOR EACH ROW
      4      WHEN (new.ID IS NULL)
      5  BEGIN
      6      :new.ID := Orders_SEQ.NEXTVAL;
      7  END;
      8  /
    
    Trigger created.
    
    SQL> insert into orders (id) values (null);
    
    1 row created.
    
    SQL> select * from orders;
    
            ID
    ----------
             1
    
    SQL>