Find Mondays between 2 dates

10.7k views Asked by At

I need to display dates of all Mondays in the given date range.

For example, if my start date is 01/05/2015 and end date is 31/05/2015, I need to show

04/05/2015
11/05/2015
18/05/2015
25/05/2015

How is it possible?

4

There are 4 answers

1
SQL Police On BEST ANSWER

This procedure is independent from regions and languages.

Please note the first line with SET DATEFIRST 1.

SET DATEFIRST 1; -- First day of the week is set to monday

DECLARE @DateFrom DateTime ='20150601', @DateTo DateTime = '20150630' ;

WITH CTE(dt)
AS
(
      SELECT @DateFrom
      UNION ALL
      SELECT DATEADD(d, 1, dt) FROM CTE
      WHERE dt < @DateTo
)
SELECT dt FROM CTE  where datepart ("dw", dt) = 1;
2
Shashank Raj Chavan On
SET DATEFIRST 7; -- Set's sunday as first day of week, won't work otherwise

DECLARE @StartDate DATE = '06/01/2015'

DECLARE @EndDate DATETIME = '06/30/2015'

DECLARE @TableOfDates TABLE(DateValue DATETIME)

DECLARE @CurrentDate DATETIME

SET @CurrentDate = @startDate

WHILE @CurrentDate <= @endDate
BEGIN
    INSERT INTO @TableOfDates(DateValue) VALUES (@CurrentDate)

    SET @CurrentDate = DATEADD(DAY, 1, @CurrentDate)
END

SELECT * FROM @TableOfDates WHERE DATEPART(weekday,Datevalue) = 2
4
Hysteria86 On

Using a CTE it is possible this way..

DECLARE @DateFrom DateTime ='2015-05-01',
        @DateTo DateTime = '2015-05-31'

;WITH CTE(dt)
AS
(
      SELECT @DateFrom
      UNION ALL
      SELECT DATEADD(d, 1, dt) FROM CTE
      WHERE dt < @DateTo
)
SELECT 'Monday', dt FROM CTE
WHERE DATENAME(dw, dt) In ('Monday')
0
Saravana Kumar On

Refer: Select dates of a day between two dates.

SELECT [Day],[Dt] FROM dbo.fnGetDatesforAday('7/1/2008','8/31/2008','Sunday')


CREATE FUNCTION fnGetDatesforAday
(
      -- Add the parameters for the function here
      @DtFrom DATETIME,
      @DtTo DATETIME,
      @DayName VARCHAR(12)
)

RETURNS @DateList TABLE ([Day] varchar(20),Dt datetime)

AS
BEGIN
      IF NOT (@DayName = 'Monday' OR @DayName = 'Sunday' OR @DayName = 'Tuesday' OR @DayName = 'Wednesday' OR @DayName = 'Thursday' OR @DayName = 'Friday' OR @DayName = 'Saturday')
      BEGIN
            --Error Insert the error message and return

            INSERT INTO @DateList
            SELECT 'Invalid Day',NULL AS DAT
            RETURN
      END 

      DECLARE @TotDays INT
      DECLARE @CNT INT

      SET @TotDays =  DATEDIFF(DD,@DTFROM,@DTTO)-- [NO OF DAYS between two dates]

      SET @CNT = 0
      WHILE @TotDays >= @CNT        -- repeat for all days 
      BEGIN
        -- Pick each single day and check for the day needed
            IF DATENAME(DW, (@DTTO - @CNT)) = @DAYNAME
            BEGIN
                  INSERT INTO @DateList
                 SELECT @DAYNAME,(@DTTO - @CNT) AS DAT
            END
            SET @CNT = @CNT + 1
      END
      RETURN
END