Reputation: 886
I have some data as follows
Duration Start Date
==========================
2 11/11/2014
1 11/6/2014
3 11/22/2014
I want to iterate to all the above three rows and produce an output as follows
Date
===========
11/11/2014
11/12/2014
11/6/2014
11/22/2014
11/23/2014
11/24/2014
Take the start date increment the date by duration and create separate rows for each dates
Upvotes: 1
Views: 1957
Reputation: 460288
Don't iterate but use set based approaches like ...
WITH Nums AS(
SELECT DISTINCT Value = number
FROM master..[spt_values]
)
SELECT Date = DATEADD(d, n.Value - 1, t.[Start Date])
FROM Nums n CROSS JOIN TableName t
WHERE n.Value BETWEEN 1 AND t.Duration
Note that this approach works only until 2,164. Another approach is to use a number-table. Read:
http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1
If you want to insert it into another table you can use it in this way:
WITH Nums AS(
SELECT DISTINCT Value = number
FROM master..[spt_values]
)
INSERT INTO #TempTable ([Date])
SELECT Date = DATEADD(d, n.Value - 1, t.[Start Date])
FROM Nums n CROSS JOIN TableName t
WHERE n.Value BETWEEN 1 AND t.Duration
Upvotes: 5