I have a payment_schedule table:
CREATE TABLE [dbo].[scheduled_transaction](
[id] [int] IDENTITY(1,1) NOT NULL,
[description] [varchar](20) NOT NULL,
[account_id] [int] NOT NULL,
[account_transaction_type_id] [int] NOT NULL,
[third_party_id] [int] NOT NULL,
[first_payment_date] [date] NOT NULL,
[last_payment_date] [date] NULL,
[payment_frequency] [int] NOT NULL,
[payment_frequency_type_id] [int] NOT NULL,
[payment_amount] [decimal](18, 2) NOT NULL,
[notes] [varchar](100) NULL,
[deleted] [datetime] NULL,
[createuser] [int] NOT NULL,
[createdate] [datetime] NOT NULL,
[lastupdateuser] [int] NULL,
[lastupdatedate] [datetime] NULL) ON [PRIMARY]
)
This table holds scheduled bill payments for my home system. The frequency is simply Daily, weekly or monthly. So, payment frequency = 1, and payment frequency type = 3 (monthly) means that the payment is done every one month.
I also have a calendar table, which is a table of all dates between a large period (2000 and 2040). This is just a reference table that I think is useful for what I will be doing.
What I want to do now, is create a procedure that will return a table of dates from a given startdate to a given enddate, and for each date, return any payments that should be done on that date, based on my schedule table.
My plan is to create a temp table with all dates where payments will be due:
DECLARE @StartDate DATE
DECLARE @EndDate DATE
Set @StartDate = '01-JAN-2013'
SET @EndDate = '31-DEC-2013'
DECLARE @Schedule TABLE
(
ID INT NOT NULL IDENTITY(1,1),
TransactionDate DATE NOT NULL,
scheduled_transaction_id INT NOT NULL
)
Once that's populated, I can then use the calendar table and create a balance forecast.
But, getting the data into that table is tricky.
I think I need to go through each scheduled_transaction, and then, run through the calendar and see if a transaction would be done on that date? And then insert the row into my temp table?
So, then I think it would be nested cursors. For each scheduled_transaction row, then for each calendar row, and use some form of 'DATEADD' or something?
Could anyone assist me with this?