Translate

Sunday, August 7, 2016

MUTATING TABLE dan TRIGGER



MUTATING TABLE dan TRIGGER


Buat tabel CHILD dan tabel PARENT

drop index RELATIONSHIP_1_FK

drop table CHILD cascade constraints

drop table PARENT cascade constraints

create table PARENT  (
IDP                  INTEGER                          not null,
constraint PK_PARENT primary key (IDP)
)

create table CHILD  (
   IDC                  INTEGER                          not null,
   IDP                  INTEGER                          not null,
   constraint PK_CHILD primary key (IDC),
   constraint FK_CHILD_RELATIONS_PARENT foreign key (IDP)
         references PARENT (IDP)
)

create index RELATIONSHIP_1_FK on CHILD (
   IDP ASC
)

Buat tabel SUMCHILD
drop table SUMCHILD cascade constraints

create table SUMCHILD  (
   IDPARENT             INTEGER                          not null,
   JUMLAH               INTEGER,
   constraint PK_SUMCHILD primary key (IDPARENT)
)


Trigger isiIDPARENT
Ket : untuk menambah record tabel SumChild dengan nilai IDP yang baru pada kolom IDParent dan 0 untuk kolom Jumlah jika ada penambahan record tabel Parent
CREATE OR REPLACE TRIGGER ISIIDPARENT
 before INSERT ON PARENT
  for each row
BEGIN

 INSERT INTO SumChild values(:New.IDP,0);
END ISIIDPARENT;


Trigger count_child
Ket : untuk mengupdate tabel SumChild pada record dengan IDParent sama dengan ID yang baru, kolom jumlah diupdate jika ada penambahan child baru.
CREATE OR REPLACE TRIGGER count_child
after INSERT ON CHILD
FOR EACH ROW
BEGIN
       update SumChild set JUMLAH=JUMLAH+1 where IDParent=:new.IDP;
END count_child;


Trigger updatep
Ket: untuk mengupdate tabel CHILD pada kolom IDP dan SumChild untuk kolom IDParent jika IDP pada tabel Parent diupdate.
CREATE OR REPLACE TRIGGER updatep
 AFTER UPDATE ON PARENT
for each row
DECLARE
begin  
         update child set idp=:new.idp where idp=:old.idp;
         update SumChild set IDParent=:new.idP where IDParent=:old.idp;

END updatep;


Trigger DeleteP
Ket: untuk menghapus record tabel Child jika mempunyi child kemudian hapus record pada tabel SumChild. Jika tidak memiliki child langsung hapus record SumChild.
CREATE OR REPLACE TRIGGER DeleteP
 before DELETE ON PARENT
FOR EACH ROW
declare
jum int ;
BEGIN
       select jumlah into jum from sumchild where idparent=:old.idp; 
       if jum>0 then
       
             delete from child where idP=:old.idP;
             delete from sumchild where idParent=:old.idp;
                                     
       else
             delete from sumchild where idParent=:old.idp;
       
       end if;
       
END DeleteP;

Trigger DeleteC
Ket: untuk mengupdate tabel SumChild kolom jumlah decrement jika child dihapus.
CREATE OR REPLACE TRIGGER deleteC
 before DELETE ON CHILD
 for each row
BEGIN
       update sumchild set jumlah=jumlah-1 where idparent=:old.idp;
  
END deleteC;

No comments:

Post a Comment

silahkan membaca dan berkomentar