Link to home
Create AccountLog in
Avatar of chaleastale
chaleastale

asked on

How can I get all mondays on the last six months using SQL server query

In SQL Server 2005, I would like to get all mondays in the last 6 months. The query should return me the dates on which all mondays in the last 6 months are happenig.

How can I create such a query?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of brad2575
brad2575
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Here you go this is all combined.  It finds the first monday going forward from the current date

Then gets the past 6 months worth of mondays from that date.

--datepart = Sunday = 1, Saturday = 7
 
DECLARE @WorkingDate as datetime
DECLARE @FirstMondayDate as datetime
DECLARE @EndDate as datetime
DECLARE @DayOfWeekLookingFor as int
 
-- set to the first StartDate you want for the first Sunday
Set @WorkingDate = GetDate()
Set @FirstMondayDate = ''
 
-- for monday
Set @DayOfWeekLookingFor = 2 
 
-- do this to find the number of the days of week found 
while @FirstMondayDate = ''
	Begin 
		-- if day of week matches what we are looking for add one to counter
		IF datepart(weekday, @WorkingDate) = @DayOfWeekLookingFor
			Set @FirstMondayDate = @WorkingDate
		
		-- increment date by one day and loop again
		Set @WorkingDate = DATEADD (dd, 1, @WorkingDate)		
		
	end
 
-- set the enddate to 6 months from the first monday we found
Set @EndDate = DATEADD (mm, -6, GetDate())
 
-- set working date to the first monday date we found above for next loop
Set @WorkingDate = @FirstMondayDate
 
 
 
-- this loops through from the first day found above to the last one requested
-- do till the end date you wnat reached
while @WorkingDate > @EndDate
        Begin 
                -- insert current working Monday date, and then add 6 to that to get the next saturday (ending dat)
                --Insert Into DatabaseTableName
                --(MondayDate)
                --Values(@WorkingDate, DATEADD (dd, 7, @WorkingDate))
				
				-- just select the date
                select @WorkingDate
 
                -- increment sunday date for next loop
                Set @WorkingDate = DATEADD (dd, -7, @WorkingDate)                
                --print @WorkingDate
        end

Open in new window