Wednesday, January 25, 2012

Trigger - Insert Data From One Table to Second

Step 1 -  Create Two tables as discussed
------------------------------


CREATE TABLE ITEM_MASTER (ITEM NUMBER, QTY NUMBER)

CREATE TABLE APPS.ITEM_TEMP
(
  ITEM1  NUMBER,
  QTY1   NUMBER
)


Step 2 - Write a trigger
------------------------------
CREATE or REPLACE TRIGGER preet_item
BEFORE delete or insert or update on item_master
FOR EACH ROW
    Declare
         l_flag number :=0 ;
    BEGIN
   
   
      SELECT NVL(SUM(QTY1),0)
      INTO L_FLAG
      FROM ITEM_TEMP WHERE ITEM1 = :NEW.ITEM;
     
      DBMS_OUTPUT.PUT_LINE(L_FLAG) ;
   
        iF L_FLAG > 0 THEN 
           -- if UPDATING then
                UPDATE item_temp
                SET item1 = :new.item
                , qty1 = (l_flag + :NEW.QTY)
                where item1 = :NEW.ITEM;
           -- end if;
       ELSE
            if INSERTING then
                INSERT INTO item_temp
                VALUES( :new.item
                , :NEW.QTY);
            end if;
       END IF;    
    end;

Step 3 - Testing  ( Run Following Inserts and After Each run check Table data )
--------------------------------------------------------------------

SELECT * FROM item_temp

SELECT * FROM item_master

insert into item_master values (11, 6)

insert into item_master values (11,-1)

insert into item_master values (11, -2)

insert into item_master values (11, 1)

insert into item_master values (12, 1)

insert into item_master values (12, 4)

insert into item_master values (12, -2)