
/* Code Fragment 5.22 Coalesce INCUMBENTS while removing duplicates (using a cursor). */

/*
CREATE TABLE Tempo 
(
	SSN CHAR(11),
	PCN CHAR(6), 
	START_DATE DATETIME, 
	END_DATE DATETIME
)
*/


DECLARE Inc_Cursor CURSOR
FOR
SELECT *
FROM INCUMBENTS
ORDER BY SSN, PCN, START_DATE


DECLARE @S_SSN CHAR(11)
DECLARE @S_PCN CHAR(6)
DECLARE @S_START_DATE DATETIME
DECLARE @S_END_DATE DATETIME

DECLARE @P_SSN CHAR(11)
DECLARE @P_PCN CHAR(6)
DECLARE @P_START_DATE DATETIME
DECLARE @P_END_DATE DATETIME

DECLARE @C_SSN CHAR(11)
DECLARE @C_PCN CHAR(6)
DECLARE @C_START_DATE DATETIME
DECLARE @C_END_DATE DATETIME

BEGIN
	OPEN Inc_Cursor

	FETCH NEXT FROM Inc_Cursor INTO @P_SSN,@P_PCN,@P_START_DATE,@P_END_DATE

	SELECT @S_SSN = @P_SSN
	SELECT @S_PCN = @P_PCN
	SELECT @S_START_DATE = @P_START_DATE
	SELECT @S_END_DATE = @P_END_DATE

	FETCH NEXT FROM Inc_Cursor INTO @C_SSN,@C_PCN,@C_START_DATE,@C_END_DATE

	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		IF 	((@S_SSN <> @C_SSN AND @S_PCN <> @C_PCN) OR
			 (@P_END_DATE < @C_START_DATE))
		BEGIN
			INSERT INTO Tempo
			VALUES (@S_SSN,@S_PCN,@S_START_DATE,@P_END_DATE)
			SELECT @S_SSN = @C_SSN
			SELECT @S_PCN = @C_PCN
			SELECT @S_START_DATE = @C_START_DATE
			SELECT @S_END_DATE = @C_END_DATE
		END	
		SELECT @P_SSN = @C_SSN
		SELECT @P_PCN = @C_PCN
		SELECT @P_START_DATE = @C_START_DATE
		SELECT @P_END_DATE = @C_END_DATE

		FETCH NEXT FROM Inc_Cursor INTO @C_SSN,@C_PCN,@C_START_DATE,@C_END_DATE
	END

	IF 	((@S_SSN <> @C_SSN AND @S_PCN <> @C_PCN) OR (@P_END_DATE < @C_START_DATE))
	BEGIN
		INSERT INTO Tempo
		VALUES (@S_SSN,@S_PCN,@S_START_DATE,@P_END_DATE)
	END

	CLOSE Inc_Cursor
END
