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?
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?
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
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
This procedure is independent from regions and languages.
Please note the first line with
SET DATEFIRST 1
.