I have a table that looks something like this (simplified):
*ScheduledReports* ReportID StartDate Frequency Interval (1=months, 2=days)
So, if I wanted to run the report every 3 days, the frequency would be 3, and the interval would be 2.
I am trying to write a stored procedure that we can run once a day, which will run all the reports from the table that is scheduled for today (or should have been started since the last time the stored procedure was run).
The stored procedure also has access to lastRunTime (the last time this stored procedure was run).
This is what my query looks like:
-- get monthly reports that should be run SELECT reportID FROM ScheduledReports WHERE intervalType = 1 AND dateadd(m, ( frequency * ceiling(( --sql server calculates datediff of months based on the actual int of the month --not if it a true month later, so the following is necessary to check for --a dayOfMonth difference CASE WHEN startDate > @lastRunTime THEN 0 WHEN day(startDate) > day(@lastRunTime) THEN datediff(m, startDate, @lastRunTime) - 1 ELSE datediff(m, startDate, @lastRunTime) END ) / (frequency*1.0)) ), startDate) BETWEEN @lastRunTime AND getDate() UNION ALL -- get weekly reports that should be run SELECT reportID FROM ScheduledReports WHERE intervalType = 2 AND dateadd(d, ( frequency * ceiling(( CASE WHEN startDate > @lastRunTime THEN 0 ELSE datediff(d, startDate, @lastRunTime) END ) / (frequency*1.0) )), startDate) BETWEEN @lastRunTime AND getDate()
However, there is something with logic. What is wrong with my logic? How can i do this?
source share