Ok, you asked for it.. --<TSQL>--...If Not Exists(Select * From [Central Staging]..ProcessStepData where SpID = @@ProcID)Begin Insert [Central Staging]..ProcessStepData Values (@@ProcID, Null, Null, @StartDate) EndElseBegin -- Only delete last step from the table Select @StartDate = DateValue From [Central Staging]..ProcessStepData where SpID = @@ProcIDEndSet Transaction Isolation Level SerializableWhile (@StartDate <= @EndDate) And @tiDudCounter < 5Begin Begin Transaction Delete Central.Dbo.IbesEstMonthEndData Where DateMonthEnd = @StartDate And (((MeasureID = @iMeasure) And (@iMeasure Is Not Null)) Or (@iMeasure Is Null)) INSERT INTO Central.Dbo.IbesEstMonthEndData Select M.EntityID, M.BrokerID, M.AnalystID, M.CurrID, M.EpiID, M.MeasureID, M.Value, M.AdjFactor, M.DatePeriodEnd, D.DateMonthEnd, M.DateEstimate FROM Central.dbo.IbesEstData M Inner Join (Select E.EntityID, E.BrokerID, E.AnalystID, E.CurrID, E.EpiID, E.MeasureID, E.DatePeriodEnd, max(E.DateEstimate) as DateEstimate, @StartDate as DateMonthEnd From Central.dbo.IbesEstData E Left Join ( Select EntityID, DatePeriodEnd, DateReported From Central.dbo.IbesActualData Where FreqID = 1 and DateReported is not null And (((MeasureID = @iMeasure) And ( @iMeasure is not null)) Or (@iMeasure is null))) A On E.EntityID = A.EntityID and E.DatePeriodEnd = A.DatePeriodEnd Where (((MeasureID = @iMeasure) And ( @iMeasure is not Null )) Or (@iMeasure is null)) -- The most important condition here -- Period End Date + 2 months MUST be >= the Month End(StartDate) AND -- Estimate Date is within 2 months of the Month End(StartDate) and the Report Date is >= the Month End -- OR If the Month End is NULL then Estimate Date is within 2 months of the Month End AND (((datediff(m, E.DateEstimate, @StartDate) <= 2) and A.DateReported >= @StartDate and (A.DateReported is not null)) OR ((datediff(m, E.DateEstimate, @StartDate) <= 2) and (A.DateReported is null)) And (Dateadd(m, 2, E.DatePeriodEnd) >= @StartDate )) Group BY E.EntityID, E.BrokerID, E.AnalystID, E.CurrID, E.EpiID, E.MeasureID, E.DatePeriodEnd ) D ON M.EntityID = D.EntityID AND M.BrokerID = D.BrokerID AND M.AnalystID = D.AnalystID AND M.CurrID = D.CurrID AND M.EpiID = D.EpiID AND M.MeasureID = D.MeasureID AND M.DatePeriodEnd = D.DatePeriodEnd And M.DateEstimate = D.DateEstimate If @@RowCount = 0 Set @tiDudCounter = @tiDudCounter + 1 Else Set @tiDudCounter = 0 Commit Transaction select @StartDate = Dateadd(dd,-1, dateadd(mm, 2, cast(year(@StartDate) as varchar(4)) + '/' + cast(month(@StartDate) as varchar (2)) + '/01')) Update [Central Staging]..ProcessStepData Set IntValue = Null, StrValue = Null, DateValue = @StartDate where SpID = @@ProcIDEnd...--<TSQL>--
Basically the I tried the dynamic SQL on the INSERT statement without the begin/commit tran. What do you think?==================================================Do not argue with IDIOTS. They will take you down to their level and BEAT you with experience.Master Fisherman