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|PR O_ID|MD_NU M|AID
00010020100|2011-05-01|201 1-08-31|10 40160053|M K332|BSD
00010020100|2012-01-01|201 2-06-30|10 40160044|F K172|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|MK33 2|BSD
2011-06-01|1040160053|MK33 2|BSD
2011-07-01|1040160053|MK33 2|BSD
2011-08-01|1040160053|MK33 2|BSD
2011-05-01|1040160053|MK33 2|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|FK17 2|ASM
2012-02-01|1040160044|FK17 2|ASM
2012-03-01|1040160044|FK17 2|ASM
2012-04-01|1040160044|FK17 2|ASM
2012-05-01|1040160044|FK17 2|ASM
2012-06-01|1040160044|FK17 2|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
The data looks like this:
SUB_ID|EFF_DTE|TERM_DTE|PR
00010020100|2011-05-01|201
00010020100|2012-01-01|201
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|MK33
2011-06-01|1040160053|MK33
2011-07-01|1040160053|MK33
2011-08-01|1040160053|MK33
2011-05-01|1040160053|MK33
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|FK17
2012-02-01|1040160044|FK17
2012-03-01|1040160044|FK17
2012-04-01|1040160044|FK17
2012-05-01|1040160044|FK17
2012-06-01|1040160044|FK17
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Great example, aided me in understanding iteration in sql server!