Find last sunday

前端 未结 10 1316
余生分开走
余生分开走 2020-12-05 20:40

How will you find last sunday of a month in sql 2000?

10条回答
  •  忘掉有多难
    2020-12-05 21:02

    I find some of these solutions hard to understand so here's my version with variables to explain the steps.

    ALTER FUNCTION dbo.fn_LastSundayInMonth
    (
      @StartDate DATETIME
     ,@RequiredDayOfWeek INT    /* 1= Sunday */
    )
    RETURNS DATETIME
    AS
    /*
    A detailed step by step way to get the answer...
    
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,1)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,2)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,3)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,4)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,5)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,6)
    SELECT dbo.fn_LastSundayInMonth(getdate()-31,7)
    */
    BEGIN
        DECLARE @MonthsSince1900 INTEGER
        DECLARE @NextMonth INTEGER
        DECLARE @DaysToSubtract INTEGER
        DECLARE @FirstDayOfNextMonth DATETIME
        DECLARE @LastDayOfMonthDayOfWeek INTEGER
        DECLARE @LastDayOfMonth DATETIME
        DECLARE @ReturnValue DATETIME
    
        SET @MonthsSince1900=DateDiff(month, 0, @StartDate)
        SET @NextMonth=@MonthsSince1900+1
        SET @FirstDayOfNextMonth = DateAdd(month,@NextMonth, 0)
        SET @LastDayOfMonth = DateAdd(day, -1, @FirstDayOfNextMonth)
    
        SET @ReturnValue = @LastDayOfMonth
    
        WHILE DATEPART(dw, @ReturnValue) <> @RequiredDayOfWeek
            BEGIN
                SET @ReturnValue = DATEADD(DAY,-1, @ReturnValue)
            END
    
        RETURN @ReturnValue
    END
    

提交回复
热议问题