Search code examples
phporaclepear

Creating Trigger long after table creation


I would like to find out what the consquence is if you want to create a sequence after a table has been created and quite a bit of data already been inserted.

( this is because PEAR's DataObject's insert() method sometimes skips incremental IDs )

So here is an example to achieve this, but is this the correct way to do if after the amount of time has passed?

Table definition:

CREATE TABLE departments (
  ID           NUMBER(10)    NOT NULL,
  DESCRIPTION  VARCHAR2(50)  NOT NULL);

ALTER TABLE departments ADD (
  CONSTRAINT dept_pk PRIMARY KEY (ID));

CREATE SEQUENCE dept_seq;

Trigger definition:

CREATE OR REPLACE TRIGGER dept_bir 
BEFORE INSERT ON departments 
FOR EACH ROW

BEGIN
  SELECT dept_seq.NEXTVAL
  INTO   :new.id
  FROM   dual;
END;

Solution

  • If you mean that you already have datas with ID field inserted without using the trigger, the only thing you'll have to check is that the "start" of your sequence = at least the max existing ID + 1

    CREATE SEQUENCE dept_seq
     START WITH     2503
     INCREMENT BY   1
    

    Then it should be perfectly fine.