Wednesday, January 15, 2014

Trigger assigned Primary Key values from the DB sequence

Create a table :


CREATE TABLE tbl_trg_key
(
   tbl_id    NUMBER,
   tbl_msg   VARCHAR2 (500),
   CONSTRAINT tbl1_trg_key_pk PRIMARY KEY (tbl_id)
);

Create a sequence :


CREATE SEQUENCE tbl_trg_key_s MINVALUE 1
                              MAXVALUE 999999999999999999999999999
                              INCREMENT BY 1
                              START WITH 100
                              NOORDER
                              NOCYCLE;
Create the trigger :


CREATE OR REPLACE TRIGGER primary_key_trg
   BEFORE INSERT
   ON tbl_trg_key
   FOR EACH ROW
BEGIN
   IF :new.tbl_id IS NULL OR :new.tbl_id < 0
   THEN
      SELECT tbl_trg_key_s.NEXTVAL INTO :new.tbl_id FROM DUAL;
   END IF;
END;
/

Create the Entity Object on the table tbl_trg_key.From the entity object , select the primary key. From the details tab change the type to DBSequence and provide the Sequence Name.Following diagram show the settings :
Refresh on Insert option is set.Give the sequence name and starts at value.Run BC tester and commit after adding row



No comments:

Post a Comment