完成這個要求之前,可以先參考另外一個函數《獲取當月的天數列表》https://www.cnblogs.com/insus/p/10837900.html: 然後要知道標題三個節日的常識,母親節在每年5月份的第二個星期天,父親節在每年6月份的第三個星期天,而感恩節是在每年的11月份第四個星期的星期四。 ...
完成這個要求之前,可以先參考另外一個函數《獲取當月的天數列表》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 GOSource Code
下麵是列出2019至2025年所有以上三個節日的日期,幫忙檢查一下,是否正確?