Skip to content

Instantly share code, notes, and snippets.

@shadyrudy
Created August 14, 2021 21:02
Show Gist options
  • Save shadyrudy/932cb480a30d08e12b59458073d34eab to your computer and use it in GitHub Desktop.
Save shadyrudy/932cb480a30d08e12b59458073d34eab to your computer and use it in GitHub Desktop.
Loop over a date range in SQL Server
declare @StartDate date
declare @EndDate date
declare @OverallEndDate date
declare @PrintStart varchar(10)
declare @PrintEnd varchar(10)
-- Set the start date and overall end date
-- Set the end date to 7 days after the start date
set @OverallEndDate = '2018-12-31'
set @StartDate = '2018-01-01'
set @EndDate = dateadd( dd,7 ,@startDate)
-- Loop while the start date is less than the overall end date
while(@OverallEndDate > @StartDate)
begin
-- Print the working weeks
set @PrintStart = CONVERT( varchar(10),@StartDate, 120)
set @PrintEnd = CONVERT( varchar(10),@EndDate, 120)
raiserror('Working on %s to %s' ,10, 1,@PrintStart ,@PrintEnd)
-- Do something here
-- select [SalesOrderID]
-- from [Sales].[SalesOrderHeader]
-- where [OrderDate] >= @StartDate
-- and [OrderDate] < @EndDate
-- Increment the weeks
set @StartDate = @EndDate
set @EndDate = dateadd( dd,7 ,@startDate)
end
raiserror('Finished!' ,10, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment