Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing Dates in batches of 7 days to a stored proc until the last 7 days

So I have stored proc which will be used to retrieve data that will be imported into another table for a long period. ‘2020-01-01’ to ‘2022-02-28’ I want to do this in batches of 7 days. I don’t want to manually run the PROC and pass 7 days range for a 2 year period.

Pseudo example:

INSERT INTO dbo.MyImportedData
INSERT INTO dbo.MyImportedData
EXEC [dbo].[MyLongRangeData]
          @StartDate = @StartDate,
          @EndDate = @EndDate -- First 7 Day Period (2020-01-01 to 2020-01-07)

INSERT INTO dbo.MyImportedData
EXEC [dbo].[MyLongRangeData]
          @StartDate = @StartDate,
          @EndDate = @EndDate -- second 7 Day Period (2020-01-08 to 2020-01-14) --Doing this until 2022-02-28.

Thanks in advance for help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming you just want simple 7-day blocks and don’t need to align to the first day of the year or fiscal periods, you could do a simple loop, something like this:

DECLARE @d date = '20200101', @e date;

WHILE @d <= '20220228'
BEGIN
  SET @e = DATEADD(DAY, 6, @d);

  INSERT dbo.MyImportedData(<always list columns here!>)
    EXEC [dbo].[MyLongRangeData] @StartDate = @d, @EndDate = @e;

  SET @d = DATEADD(DAY, 7, @d);
END

But better would be to re-write the procedure (or create a new one) to handle 7-day chunks for you across any date range, so you don’t have to call it 100 times.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading