编辑:我忽略了 Oracle 标记的存在,并开始为 SQL Server 编写脚本。但是这个概念并没有改变。
为了超级准确,我会创建一个如下格式的表格。
Year int, month int, DaysInMonth int, firstOccuranceOfSunday int
创建一个过程以从该表上的特定年份和月份中提取周末。
CREATE FUNCTION [dbo].[GetWeekendsForMonthYear]
(
@year int,
@month int
)
RETURNS @weekends TABLE
(
[Weekend] date
)
AS
BEGIN
declare @firstsunday int = 0
Declare @DaysInMonth int = 0
Select @DaysInMonth = DaysInMonth, @firstsunday = FirstSunday from Months
Where [Year] = @year and [month] = @month
Declare @FirstSaterday int = @firstsunday - 1
declare @CurrentDay int = 0
Declare @CurrentDayIsSunday bit = 0
if @FirstSaterday !< 1
Begin
insert into @Weekends values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @Firstsaterday -1, 0))))
insert into @Weekends values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @FirstSunday -1, 0))))
set @CurrentDayIsSunday = 1
set @CurrentDay = @firstsunday
END
else
begin
insert into @Weekends values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @FirstSunday -1, 0))))
set @FirstSaterday = @firstsunday + 6
insert into @Weekends values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @Firstsaterday -1, 0))))
set @CurrentDayIsSunday = 0
set @CurrentDay = @FirstSaterday
end
declare @done bit = 0
while @done = 0
Begin
if @CurrentDay <= @DaysInMonth
Begin
If @CurrentDayIsSunday = 1
begin
set @CurrentDay = @CurrentDay + 6
set @CurrentDayIsSunday = 0
if @CurrentDay <= @DaysInMonth
begin
insert into @Weekends Values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @CurrentDay -1, 0))))
end
end
else
begin
set @CurrentDay = @CurrentDay + 1
set @CurrentDayIsSunday = 1
if @CurrentDay <= @DaysInMonth
begin
insert into @Weekends Values(DATEADD(year, @year -1900, DATEADD(month, @month -1, DATEADD(day, @CurrentDay -1, 0))))
end
end
end
ELSE
begin
Set @done = 1
end
end
RETURN
END
当调用并提供年份和月份时,这将返回代表周末的日期列表。
现在,使用该函数,创建一个过程,为特定日期范围内的每个适用行调用一次该函数,并在临时表中返回值。
请注意,我现在发布此内容,以便您查看发生了什么,但我将继续处理代码。当它们出现时,我会发布更新。
更多内容:获取特定日期范围的周末列表(格式化),从该列表中删除可以在您的假期表中找到的所有日期。
很遗憾,我明天还要上班,我要睡觉了。