ORACLE Table Trigger ID

November 30, 2012 10:23 pm Published by

Sotto un esempio di come realizzata una tabella con associato un trigger sul campo chiave IDT, con un relativo TRIGGER che provvede con l’omonima SEQUENCE a valorizzare in automatico tale campo.

CREATE SEQUENCE TAB1_SRL
  START WITH 1
  MAXVALUE 999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 4
  NOORDER;

CREATE TABLE TAB1
(
  IDT           NUMBER(10)            NOT NULL,
  CAMPO1    CHAR(30 BYTE)                  NOT NULL,
  CAMPO2    NUMBER(10)                    NOT NULL,
  UTD           CHAR(16 BYTE),
  DTA           DATE
);


CREATE OR REPLACE TRIGGER TAB1_SRL
  before insert ON TAB1 for each row
declare
  n_new number(12) := 0;
  n_inc number(12) := 0;
begin
  if (:new.IDT=0) or (:new.IDT is null) then
     select TAB1_SRL.nextval into n_new from dual;
  else
     n_new := :new.IDT;
     n_inc := 1;
     loop
        exit when n_inc>=n_new;
        select TAB1_SRL.nextval into n_inc from dual;
     end loop;
  end if;
  :new.IDT := n_new;
end;
/

Categorised in: ,

This post was written by admin

Comments are closed here.