获知某一年的母亲节,父亲节和感恩节日期

Posted insus

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获知某一年的母亲节,父亲节和感恩节日期相关的知识,希望对你有一定的参考价值。

完成这个要求之前,可以先参考另外一个函数《获取当月的天数列表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
Source Code

 

下面是列出2019至2025年所有以上三个节日的日期,帮忙检查一下,是否正确?

技术图片

 

以上是关于获知某一年的母亲节,父亲节和感恩节日期的主要内容,如果未能解决你的问题,请参考以下文章

父亲节!程序员给父亲一份代码信

父亲节!程序员给父亲一份代码信

父亲节!程序员给父亲一份代码信

父亲节!程序员给父亲一份代码信

MySQL中, 如何查询某一天, 某一月, 某一年的数据.

判断某一年的某个月的天数