由于您使用的是 SQL Server,因此可以使用递归公用表表达式。
递归 CTE 由结合在一起的两个互补查询组成。第一个查询是为递归或循环设置初始条件的锚点,而第二个查询通过执行自引用选择来进行递归。也就是说,它在其 from 子句中引用了递归 CTE:
-- vvvvvvvvvvvv this is the Recursive CTEs name
with RecursiveCTE(Loan, Payment#, Due_Date, UPB, Int_Rate, Total_PI,
Monthly_Int_Amt, Monthly_Prin_Amt, New_UPB)
as (
-- The Anchor Query
SELECT AMS.Loan,
AMS.Payment#,
AMS.Due_Date,
AMS.UPB,
AMS.Int_Rate,
AMS.Total_PI,
AMS.Monthly_Int_Amt,
AMS.Monthly_Prin_Amt,
AMS.New_UPB
FROM #AmSchedule AMS
UNION ALL
-- The Recursive Part
SELECT Prior.Loan,
Prior.Payment# + 1, -- Increment Pay#
dateadd(mm, 1, Prior.Due_Date), -- Increment Due Date
Prior.new_UPB, -- <-- New_UPB from last iteration
Prior.Int_Rate,
Prior.Total_PI,
Prior.Monthly_Int_Amt, -- <-- Put your
Prior.Monthly_Prin_Amt, -- <-- calculations
Prior.New_UPB -- <-- here
FROM RecursiveCTE Prior
-- ^^^^^^^^^^^^ this is what makes it recursive
)
-- Output the results
select * from RecursiveCTE