我已经接受了这里给出的答案,并提出了以下数据库结构:
Column Data Type
id int
task_name nvarchar(50)
frequency_type nvarchar(10)
runat_day int
runat_month int
runat_year int
数据如下所示:
id task_name frequency_type runat_day runat_month runat_year
1 Do this Once once 16 2 2018
2 Do this Monthly monthly 31 0 0
3 Do this Yearly yearly 28 2 0
4 Do this Daily daily 0 0 0
5 Do this Weekly weekly 6 0 0
将数据拉回的查询如下所示:
DECLARE @chosen_date datetime = '2018-02-28'
DECLARE @lastDayOfMonth int = datePart(d,dateadd(s,-1,dateadd(mm, datediff(m,0,getdate())+1,0)))
select task_name
from scheduled_tasks
where (frequency_type = 'once' and runat_day = DATEPART(DAY, @chosen_date) and runat_month = DATEPART(MONTH, @chosen_date) and runat_year = DATEPART(YEAR, @chosen_date))
or frequency_type = 'daily'
or (frequency_type = 'weekly' and runat_day = DATEPART(WEEKDAY,@chosen_date))
or (frequency_type = 'monthly' and runat_day = DATEPART(DAY, @chosen_date))
or (frequency_type = 'monthly' and @lastDayOfMonth = DATEPART(DAY, @chosen_date) and runat_day >= @lastDayOfMonth)
or (frequency_type = 'yearly' and runat_day = DATEPART(DAY, @chosen_date) and runat_month = DATEPART(MONTH, @chosen_date))
到目前为止,我的所有用例都正确出现,即使是在给定月份中不存在的某一天的月末日期也得到了正确处理(例如,每个月的 31 日仍将在 2 月 28 日触发)
给定频率类型不需要的字段仅包含零或空值,并被查询忽略。
它不考虑闰年 2 月 29 日发生的年度事件,也不以任何方式考虑一天中的时间。