-- -----------------------------------------------
-- USING SQL TO DEVELOP TIME ORIENTED APPLICATIONS
-- By : Richard T. Snodgrass
-- -----------------------------------------------
--
-- Sequenced Primary Key for INCUMBENTS (closed-time)
-- INCUMBENTS is temporal
-- By   : Bruce C. Huang
-- Date : Dec. 12, 1997
--
-- Note:  There can only be 1 UPDATE/INSERT trigger
--        for table INCUMBENTS.  So future triggers
--        involving INCUMBENTS must be either
--        merged with this one or replaced.
-- -----------------------------------------------
REM
REM Code Fragment 5.5 in Oracle 7.3
REM There is no ASSERTIONS in Oracle 7.3, only Triggers.
REM
CREATE OR REPLACE TRIGGER seq_primary_key
AFTER INSERT or UPDATE on INCUMBENTS
DECLARE 
   valid             INTEGER;
BEGIN
   SELECT 1
   INTO   valid
   FROM   DUAL
   WHERE  NOT EXISTS( SELECT I1.SSN
                      FROM   INCUMBENTS I1 , INCUMBENTS I2
                      WHERE  I1.SSN = I2.SSN
                         AND I1.PCN = I2.PCN
                         AND I1.START_DATE <= I2.END_DATE
                         AND I2.START_DATE <= I1.END_DATE
                         AND I1.ROWID != I2.ROWID )
      AND NOT EXISTS( SELECT *
                      FROM  INCUMBENTS I1
                      WHERE I1.SSN IS NULL OR I1.PCN IS NULL );

  -- If this SELECT succeeds w/o raising the NO_DATA_FOUND exception,
  --   then this insert/update does not have an overlap period for a SSN 
  --   and PCN.

  EXCEPTION
     WHEN NO_DATA_FOUND THEN
        RAISE_APPLICATION_ERROR ( -20001 , 
                                  'SSN and PCN are sequenced primary keys' );
        -- Abort the offending transaction, and
        --    rollback to a consistent state.

END;
/
