The problem that I encountered in this question / answer is that it is only for one entry. In this SQL answer post, I found a simple and effective solution on how to convert a string with a date range to many rows with each date .
RichardTheKiwi's solution involves adding new date records based on an integer table (list) and joining the original table by evaluating the date range using the datediff function. You can get a list of integers directly from the SQL Server main database ( SELECT master..spt_values WHERE v.type='P' ). this is
The google search term is sql spt_values and there are many interesting blog posts about this table. For instance...
Complete solution:
--NAME | START | END --Bob | 10/30 | 11/2 DECLARE @SampleData as table (PersonName nvarchar(50), StartDate date, EndDate date) INSERT INTO @SampleData (PersonName, StartDate, EndDate) VALUES ('Bob', '2019-10-30', '2019-11-02') , ('Joe', '2019-10-30', '2019-11-05') ; WITH cteSampleData_RecordAdded AS -- NOTE: Range record converted to daily records for 'SampleData' ( SELECT T1.PersonName , T1.StartDate , T1.EndDate , DATEADD(d,v.number,T1.StartDate) AS [NewRecordDate] , DATEDIFF(day, T1.StartDate, T1.EndDate)+1 AS [QDaysActive] FROM @SampleData T1 -- Adds a record for each date in the range JOIN MASTER..spt_values v ON v.type='P'AND v.number BETWEEN 0 AND datediff(d, T1.StartDate, T1.EndDate) ) select * from cteSampleData_RecordAdded
Results:
+------------+------------+-----------+---------------+-------------+ | PersonName | StartDate | EndDate | NewRecordDate | QDaysActive | +------------+------------+-----------+---------------+-------------+ | Bob | 10/30/2019 | 11/2/2019 | 10/30/2019 | 4 | +------------+------------+-----------+---------------+-------------+ | Bob | 10/30/2019 | 11/2/2019 | 10/31/2019 | 4 | +------------+------------+-----------+---------------+-------------+ | Bob | 10/30/2019 | 11/2/2019 | 11/1/2019 | 4 | +------------+------------+-----------+---------------+-------------+ | Bob | 10/30/2019 | 11/2/2019 | 11/2/2019 | 4 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 10/30/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 10/31/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 11/1/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 11/2/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 11/3/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 11/4/2019 | 7 | +------------+------------+-----------+---------------+-------------+ | Joe | 10/30/2019 | 11/5/2019 | 11/5/2019 | 7 | +------------+------------+-----------+---------------+-------------+
source share