码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-05-12 19:37:03      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:value   sql   tar   har   感恩   over   日期   The   https   

完成这个要求之前,可以先参考另外一个函数《获取当月的天数列表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年所有以上三个节日的日期,帮忙检查一下,是否正确?

技术图片

 

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

标签:value   sql   tar   har   感恩   over   日期   The   https   

原文地址:https://www.cnblogs.com/insus/p/10853256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!