【发布时间】:2023-03-09 06:25:01
【问题描述】:
我有一个看起来像这样的表(简化):
*ScheduledReports*
ReportID
StartDate
Frequency
Interval (1=months, 2=days)
因此,如果我想每 3 天运行一次报告,频率为 3,间隔为 2。
我正在尝试编写一个我们可以每天运行一次的存储过程,它将运行表中为今天安排的所有报告(或者自我们上次运行存储过程以来应该已经运行)。
存储过程还可以访问 lastRunTime(此存储过程的最后一次运行时间)。
这是我的查询到目前为止的样子:
-- 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's 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()
不过,逻辑有些不对劲。我的逻辑有什么问题?我怎样才能做到这一点?
【问题讨论】:
-
如果上次生成报告的时间超过一天怎么办?
-
@mark bannister - 如果它应该在上次运行和今天之间的任何时间发送,我们希望发送一次
-
让您创建另一个表的解决方案是否可以接受?还是您受限于仅使用您目前拥有的东西?
标签: sql sql-server tsql logic