CSCI 5931A
Advanced Database Development
Summer 1999
Suugested Solution to Homework #4

(1)    For example:

create or replace function RootId return BinaryTree.NodeId%type is
   Result BinaryTree.NodeId%type;
begin  -- RootId
   select NodeId into Result
   from BinaryTree
   where NodeId not in (select distinct LeftChildId
                        from BinaryTree
                        where LeftChildId IS NOT NULL)
   and NodeId not in (select distinct RightChildId
                      from BinaryTree
                      where RightChildId IS NOT NULL);
   return Result;
end RootId;
/

begin  -- testing.
   dbms_output.put_line(RootId());
end;
/

(2)    For example,

drop sequence SuppliesLogSeq;
create sequence SuppliesLogSeq
   start with 100
   increment by 1;

drop table SuppliesLog;
create table SuppliesLog(
   LogId     NUMBER(8) Primary key,
   SNum      CHAR(4),
   PNum      CHAR(4),
   Quantity  NUMBER(7),
   LogType   CHAR(6),
   LogDate   DATE
);

drop table Mono;
create table Mono (
   MonoId NUMBER primary key
);
insert into Mono values (1);

create or replace trigger SuppliesLogTrigger
   after insert or delete or update on Supplies
   for each row
declare
   NewLogId NUMBER;
   Amount NUMBER;
   IsAdd BOOLEAN := TRUE;
begin -- SuppliesLogTrigger
   --  Get NewLogId.
   select SuppliesLogSeq.NextVal into NewLogId
   from Mono;

   if (inserting) then
       insert into SuppliesLog
       values (NewLogId, :new.SNum, :new.PNum, :new.Quantity, 'CREATE', SysDate);
   elsif (deleting) then
       insert into SuppliesLog
       values (NewLogId, :old.SNum, :old.PNum, :old.Quantity, 'REMOVE', SysDate);
   else -- updating.
       Amount := :new.Quantity - :old.Quantity;
       IsAdd := (Amount >= 0);
       if IsAdd then
          insert into SuppliesLog
          values (NewLogId, :old.SNum, :old.PNum, Amount, 'ADD   ', SysDate);
       else
          Amount := -Amount;
          insert into SuppliesLog
          values (NewLogId, :old.SNum, :old.PNum, Amount, 'MINUS ', SysDate);
       end if;
   end if;
end SuppliesLogTrigger;
/

insert into Supplies values ('S11', 'P4', 100);
update Supplies set Quantity = 30 where SNum = 'S11' and PNum = 'P4';
update Supplies set Quantity = 80 where SNum = 'S11' and PNum = 'P4';
delete from Supplies where SNum = 'S11' and PNum = 'P4';

select LogId, SNum, PNum,
       Quantity, LogType,
       To_Char(LogDate, 'Month DD, YYYY HH24:MI:SS') as "Logged Time"
from SuppliesLog
where SNum = 'S11' and PNum ='P4'
order by LogId;