我正在尝试编写一个sql查询,它将根据用户选择的内容,每x天每x周重复一次。因此,用户将选择希望该作业每2周在星期二重复一次,提供的值为
declare @StartDate datetime -- when the job first recurs
declare @recurrenceValue1 int -- amount of weeks
declare @recurrenceValue2 int -- day of week (mon-sun)
declare @NextOcurrance datetime -- when the job will recur我知道如何将其设置为周数:
SET @NextOccurance = (Convert(char(12),@StartDate + (@RecurrenceValue1),106))但是我不确定如何将它滚动到星期几,所以如果@startDate是今天,并且它应该在星期二每两周重复一次,那么它将看到两周今天是星期三,所以将循环,直到它知道这一天是星期二,这将是@NextRecurrance日期。
提前感谢
发布于 2011-12-17 00:35:52
向日期添加周数的一种简单方法是使用(MSDN DATEADD)
DATEADD(wk, @StartDate, @recurrenceValue1)要找出您正在查看的日期所属的星期几,您可以使用(MSDN DATEPART)
DATEPART(dw, @StartDate)此函数使用DATEFIRST确定一周中的第一天(http://msdn.microsoft.com/en-us/library/ms181598.aspx)
SET DATEFIRST 1 --Where 1 = Monday and 7 = Sunday因此,对于您的问题(DATEFIRST设置为1=星期一)..
SET DATEFIRST 1
declare @StartDate datetime -- when the job first recurs
declare @recurrenceValue1 int -- amount of weeks
declare @recurrenceValue2 int -- day of week (mon-sun)
declare @NextOcurrance datetime -- when the job will recur
SET @StartDate = '2011-12-16' -- This is a Friday
SET @recurrenceValue1 = 2 -- In 2 weeks
SET @recurrenceValue2 = 2 -- On Tuesday
SET @NextOcurrance = DATEADD(wk, @recurrenceValue1, @StartDate) -- Add our 2 weeks
/* Check if our incrementation falls on the correct day - Adjust if needed */
IF (DATEPART(dw, @NextOcurrance) != @recurrenceValue2) BEGIN
DECLARE @weekDay int = DATEPART(dw, @NextOcurrance)
SET @NextOcurrance = DATEADD(dd, ((7 - @weekDay) + @recurrenceValue2), @NextOcurrance) -- Add to @NextOcurrance the number of days missing to be on the requested day of week
END添加天数的逻辑如下:我们一周有7天,需要多少天才能到达本周末。将此天数添加到@recurrenceValue2 (我们要查找的星期几)。
PS:由于我的名声,我不能发布超过2个HyperLinks。这就是DATEFIRST URL采用纯文本的原因。
下面是一些允许以不同方式处理特定日期的代码。虽然这段代码只适用于唯一的日期。例如,如果需要跳过一整周,则使用此代码将需要为本周要跳过的每一天添加值。对于唯一日以外的范围,应修改此代码以处理日期范围或特定周和/或周中的某一天。
CREATE TABLE OccurenceExclusions (
ExclusionDate DATE not null,
NumberOfDaysToAdd int not null
PRIMARY KEY (ExclusionDate)
)
INSERT OccurenceExclusions VALUES ('2012-01-01', 7)
SET @NextOcurrance = DATEADD(dd, COALESCE((SELECT NumberOfDaysToAdd
FROM OccurrenceExclusions
WHERE ExclusionDate = @NextOcurrance), 0), @NextOcurrance)https://stackoverflow.com/questions/8504051
复制相似问题