获知某一年的母亲节,父亲节和感恩节日期
完成这个要求之前,可以先参考另外一个函数《获取当月的天数列表》https://www.cnblogs.com/insus/p/10837900.html:
然后要知道标题三个节日的常识,母亲节在每年5月份的第二个星期天,父亲节在每年6月份的第三个星期天,而感恩节是在每年的11月份第四个星期的星期四。
知道这些常识就好办了。
写一个SQL的自定义函数:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-12 -- Update date: 2019-05-12 -- Description: 获取节日日期 -- ============================================= CREATE FUNCTION [dbo].[svf_Festivals] ( @StartYear INT, @EndYear INT ) RETURNS @tempTable TABLE([ID] INT IDENTITY(1,1) PRIMARY KEY,[Year] [INT] NOT NULL,[Mother's Day] [DATETIME] NULL,[Father's Day] [DATETIME] NULL,[Thanksgiving Day] DATETIME) AS BEGIN WHILE @StartYear <= @EndYear BEGIN INSERT INTO @tempTable ([Year]) VALUES(@StartYear) UPDATE @tempTable SET [Mother's Day] = ( SELECT [Date] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [Date] ASC) AS [RowNumber], [Date] FROM [dbo].[tvf_DaysOfMonth](CAST(@StartYear AS NVARCHAR(4)) + '-05-01') WHERE DATENAME(dw,[Date]) = 'Sunday') AS md WHERE [RowNumber] = 2) WHERE [Year] = @StartYear UPDATE @tempTable SET [Father's Day] = ( SELECT [Date] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [Date] ASC) AS [RowNumber], [Date] FROM [dbo].[tvf_DaysOfMonth](CAST(@StartYear AS NVARCHAR(4)) + '-06-01') WHERE DATENAME(dw,[Date]) = 'Sunday') AS fd WHERE [RowNumber] = 3) WHERE [Year] = @StartYear UPDATE @tempTable SET [Thanksgiving Day] = ( SELECT [Date] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [Date] ASC) AS [RowNumber], [Date] FROM [dbo].[tvf_DaysOfMonth](CAST(@StartYear AS NVARCHAR(4)) + '-11-01') WHERE DATENAME(dw,[Date]) = 'Thursday') AS td WHERE [RowNumber] = 4) WHERE [Year] = @StartYear SET @StartYear = @StartYear + 1 END RETURN END GO
下面是列出2019至2025年所有以上三个节日的日期,帮忙检查一下,是否正确?