Link to home
Start Free TrialLog in
Avatar of SharonBernal
SharonBernal

asked on

SQL Server 2008: Loop/Iterate through date range while inserting

I have a scenario where I have to break the dataset down by the month and insert the results of the breakdown into a new table.

The data looks like this:
SUB_ID|EFF_DTE|TERM_DTE|PRO_ID|MD_NUM|AID
00010020100|2011-05-01|2011-08-31|1040160053|MK332|BSD            
00010020100|2012-01-01|2012-06-30|1040160044|FK172|ASM

The result needs to look like this for the first record, the range is from May to August

MONTH|PRO_ID|MD_NUM|AID
2011-05-01|1040160053|MK332|BSD
2011-06-01|1040160053|MK332|BSD
2011-07-01|1040160053|MK332|BSD
2011-08-01|1040160053|MK332|BSD
2011-05-01|1040160053|MK332|BSD

Then the data for the SUB_ID record changes and the new range is January to June, the results need to look like this:

2012-01-01|1040160044|FK172|ASM
2012-02-01|1040160044|FK172|ASM
2012-03-01|1040160044|FK172|ASM
2012-04-01|1040160044|FK172|ASM
2012-05-01|1040160044|FK172|ASM
2012-06-01|1040160044|FK172|ASM

Here's my code.

WITH RecCTE AS (
  SELECT sub_id, eff_dte
  FROM rawdata
  UNION ALL
  SELECT R.sub_id, DATEADD(day,1,R.eff_dte)
  FROM RecCTE R JOIN rawdata RD ON R.eff_dte < RD.term_dte
  )
INSERT INTO SDATA
SELECT R.sub_id, R.eff_dte
FROM RecCTE R
  JOIN (SELECT sub_id, pro_id, md_num,aid
        FROM rawdata
       ) T ON R.empid = T.empid
  JOIN (SELECT sub_id, COUNT(*) cnt
        FROM RecCTE
        GROUP BY sub_id) R2 ON R.sub_id=R2.sub_id
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of J Depp
J Depp

Great example, aided me in understanding iteration in sql server!