'***********************************************************************
'** Description : Coalescing with Cursor
'** Author      : Dhumil Sheth & Yuji Nishimura
'** Date        : December 4th, 1997
'***********************************************************************

Option Compare Database
Option Explicit

Sub coalesce()

Dim PauseTime, Start, Finish, TotalTime
    PauseTime = 5   ' Set duration.
    Start = Timer   ' Set start time.
    
Dim dbs As Database, rts As Recordset
Dim StartEID As Integer, StartSD As Date, StartED As Date
Dim PrevEID As Integer, PrevSD As Date, PrevED As Date
Dim CurrEID As Integer, CurrSD As Date, CurrED As Date

Dim execStr As String
Set dbs = CurrentDb()

dbs.execute "DROP TABLE emp11COA; "
dbs.execute "CREATE TABLE emp11COA (EID       INTEGER, " _
                      & " StartDate DATE, " _
                      & " EndDate   DATE);"

execStr = "SELECT EID, StartDate, EndDate " _
        & "FROM emp11res " _
        & "ORDER BY EID, StartDate, EndDate;"
Set rts = dbs.OpenRecordset(execStr, dbOpenSnapshot)

PrevEID = rts.Fields(0)
PrevSD = rts.Fields(1)
PrevED = rts.Fields(2)
rts.MoveNext

StartEID = PrevEID
StartSD = PrevSD
StartED = PrevED

CurrEID = rts.Fields(0)
CurrSD = rts.Fields(1)
CurrED = rts.Fields(2)
rts.MoveNext

  
Do

    If ((StartEID <> CurrEID) Or ((PrevED + 1) < CurrSD)) Then
      execStr = " INSERT INTO emp11COA " _
             & " VALUES (" + CStr(StartEID) + ",#" & Format(StartSD, "MM/DD/YY") & "#," _
             & "#" & Format(PrevED, "MM/DD/YY") & "#);"
      dbs.execute execStr
      
      StartEID = CurrEID
      StartSD = CurrSD
      StartED = CurrED
      PrevEID = StartEID
      PrevSD = StartSD
      PrevED = StartED
    End If

    If (rts.EOF) Then
       Exit Do
    End If
    
    If (CurrED > PrevED) Then
       PrevEID = CurrEID
       PrevSD = CurrSD
       PrevED = CurrED
    End If

    CurrEID = rts.Fields(0)
    CurrSD = rts.Fields(1)
    CurrED = rts.Fields(2)
    rts.MoveNext
Loop

execStr = " INSERT INTO emp20000COA " _
        & " VALUES (" + CStr(StartEID) + ",#" & Format(StartSD, "MM/DD/YY") & "#," _
        & "#" & Format(PrevED, "MM/DD/YY") & "#);"
    dbs.execute execStr

Finish = Timer  ' Set end time.
TotalTime = Finish - Start  ' Calculate total time.
MsgBox "Paused for " & TotalTime & " seconds"
    
End Sub



