CREATE TABLE #Pmts (tran_date DATETIME PRIMARY KEY CLUSTERED ,Calc_interest_accrued MONEY, Interest_paid MONEY ,TotalInterestPaid MONEY, TotalInterestAccrued MONEY ,TotalInterestDue AS (TotalInterestAccrued - TotalInterestPaid))INSERT INTO #Pmts (tran_date, Calc_interest_accrued, Interest_paid ,TotalInterestPaid, TotalInterestAccrued)SELECT '2012-09-08',54.06,NULL,0,0UNION ALL SELECT '2012-09-10',54.06,NULL,0,0UNION ALL SELECT '2012-09-11',24.04,112.35,0,0UNION ALL SELECT '2012-09-13',23.67,20.12,0,0UNION ALL SELECT '2012-09-14',23.67,NULL,0,0DECLARE @InterestPaid MONEY, @InterestAccrued MONEYSELECT @InterestPaid = 0, @InterestAccrued = 0UPDATE #PmtsSET TotalInterestPaid = ISNULL(@InterestPaid, 0) + TotalInterestPaid ,TotalInterestAccrued = TotalInterestAccrued + @InterestAccrued ,@InterestPaid = ISNULL(Interest_paid, 0) + @InterestPaid ,@InterestAccrued = @InterestAccrued + Calc_interest_accruedSELECT * FROM #PmtsDROP TABLE #Pmts
UPDATE tgt SET TotalInterestPaid = ISNULL(@InterestPaid, 0) + TotalInterestPaid ,TotalInterestAccrued = TotalInterestAccrued + @InterestAccrued ,@InterestPaid = ISNULL(Interest_paid, 0) + @InterestPaid ,@InterestAccrued = @InterestAccrued + Calc_interest_accrued FROM #Pmts tgt WITH(TABLOCKX) OPTION (MAXDOP 1);
UPDATE #Pmts WITH(TABLOCK)SET TotalInterestPaid = ISNULL(@InterestPaid, 0) + TotalInterestPaid ,TotalInterestAccrued = TotalInterestAccrued + @InterestAccrued ,@InterestPaid = ISNULL(Interest_paid, 0) + @InterestPaid ,@InterestAccrued = @InterestAccrued + Calc_interest_accruedOPTION (MAXDOP 1)