declare @fromdate date = '20170101'
declare @thrudate date = '20170105'
declare @from_UserId int = 1;
declare @thru_UserId int = 3;
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
select top (datediff(day, @fromdate, @thrudate)+1)
[Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
from n as deka cross join n as hecto cross join n as kilo
cross join n as tenK cross join n as hundredK
order by [Date]
)
insert into myTable ([Date],UserId)
select [Date], u.UserId
from dates
cross join (
select UserId
from Users u
where u.UserId >= @from_UserId
and u.UserId <= @thru_UserId
) u;
The above uses stacked ctes to generate a numbers table, and uses that numbers table to generate dates between the date range provided.
It might not look as simple as using a while
loop, but it will perform much better.
rextester demo: http://rextester.com/HHY62656
returns:
+------------+--------+
| date | userid |
+------------+--------+
| 2017-01-01 | 1 |
| 2017-01-02 | 1 |
| 2017-01-03 | 1 |
| 2017-01-04 | 1 |
| 2017-01-05 | 1 |
| 2017-01-01 | 2 |
| 2017-01-02 | 2 |
| 2017-01-03 | 2 |
| 2017-01-04 | 2 |
| 2017-01-05 | 2 |
| 2017-01-01 | 3 |
| 2017-01-02 | 3 |
| 2017-01-03 | 3 |
| 2017-01-04 | 3 |
| 2017-01-05 | 3 |
+------------+--------+
Number and Calendar table reference: