
/* Code Fragment 4.18 POSITIONS.PCN defines a contiguous history. */

CREATE TRIGGER Contiguous_History
ON POSITIONS
FOR INSERT, UPDATE, DELETE
AS
BEGIN
	IF (	EXISTS (SELECT *
			FROM POSITIONS AS P, POSITIONS AS P2
			WHERE P.PCN = P2.PCN
			AND P.END_DATE < P2.START_DATE
			AND NOT EXISTS (SELECT *
					FROM POSITIONS AS P3
					WHERE P3.PCN = P.PCN
					AND (	((P3.START_DATE <= P.END_DATE)
						AND (P.END_DATE < P3.END_DATE))
						OR ((P3.START_DATE < P2.START_DATE)
						AND (P2.START_DATE <= P3.END_DATE)))))
	   )
  	RAISERROR('Transaction violates contiguous history',1,2)
	ROLLBACK TRANSACTION
END
