This snippet is so nice, I’m posting it again!

I’ve utilized the script below at least once a week, for either reports, or working with large data sets. Rather than reinventing the wheel, I’m posting my code here and to GitHub for everyone to see.

The script expects two date parameters, a start date and an overall end date. The script will then assign a third variable, end date, seven days after the start date. The script will execute your given code. The final step inside the loop increments the start date and end date by seven days. The script will loop until the start date is greater then the overall end date.

 

As you can see, the loop iterates over all dates and completes successfully.

If you’re working with a significantly large data set, you can modify the code to increment by one day instead of seven.

Loop over two dates in SQL Server

Rudy

Rudy Rodarte is a SQL Server Database professional based in Austin, TX. Over his career, Rudy has worked with SSRS, SSIS, performance tuning troubleshooting. When away from Keyboard, Rudy goes to Spurs and Baylor Bear sporting events.

More Posts - Website - Twitter