
/* Code Fragment 9.21 Triggers for maintaining a tri-partitioned state table. */

CREATE TRIGGER INSERT_P
ON PROJECTIONS
FOR INSERT
AS
	INSERT P_TT_CURRENT
	SELECT Inserted.PROJECTION_ID, GETDATE()
	FROM Inserted


CREATE TRIGGER DELETE_P
ON PROJECTIONS
FOR DELETE
AS
BEGIN
	INSERT P_TT_PAST
	SELECT 	OLD.PROJECTION_ID, OLD.PROJECTION_NAME, OLD.PROJECTION_TYPE, OLD.SPHEROID_CODE,
		OLD.PROJECTION_UOM, OLD.ZONE_CODE, P.Start_Date, GETDATE()
	FROM Deleted AS OLD, P_TT_CURRENT AS P
	WHERE P.PROJECTION_ID = OLD.PROJECTION_ID
	
	DELETE FROM P_TT_CURRENT
	FROM Deleted
	WHERE P_TT_CURRENT.PROJECTION_ID = Deleted.PROJECTION_ID

END


CREATE TRIGGER UPDATE_P
ON PROJECTIONS
FOR UPDATE
AS
BEGIN
	INSERT P_TT_PAST
	SELECT 	OLD.PROJECTION_ID, OLD.PROJECTION_NAME, OLD.PROJECTION_TYPE, OLD.SPHEROID_CODE,
		OLD.PROJECTION_UOM, OLD.ZONE_CODE, P.Start_Date, GETDATE()
	FROM Deleted AS OLD, P_TT_CURRENT AS P
	WHERE P.PROJECTION_ID = OLD.PROJECTION_ID

	UPDATE P_TT_CURRENT
	SET Start_Date = GETDATE()
	FROM Inserted AS NEW
	WHERE P_TT_CURRENT.PROJECTION_ID = NEW.PROJECTION_ID
END
