How do I fill a temp table iteratively and stuff() the result into columns?
<p>If I want to know for each user how much time they spent on the intranet on a certain day, I can use a custom function - 2 examples:</p>

<pre><code>select * from [dbo].[usertime]('2016-04-08')

userid  totaltime
-----------------
1       4430
2       11043
5       13045


select * from [dbo].[usertime]('2016-04-09')

userid  totaltime
-----------------
1       345
3       12066
9       15344
</code></pre>

<p>I have no control over the function and can only use its output. The <code>totaltime</code> is in seconds.</p>

<p>From another table, I can select the dates in a year:</p>

<pre><code>select * from dates;

date
----------
2016-01-01
...
2016-04-08
2016-04-09
</code></pre>

<p>I would like to run the custom function <code>usertime</code> for each <code>date</code> in the <code>dates</code> table and store the result in a temp table, as follows:</p>

<pre><code>userid  2016-01-01  ..  2016-04-08  2016-04-09
----------------------------------------------
1       ..              4430        345
2       ..              11043       0
3       ..              0           12066
5       ..              13045       0
9       ..              0           15344
</code></pre>

<p>This would require me to call <code>usertime</code> in a loop, pseudo:</p>

<pre><code>create table #usertime
(
    userid  int
    date    date
    seconds int
)

select * into #dates from dates;

foreach (#dates as _date)
    update #usertime with [dbo].[usertime](_date)

select * from #usertime

userid  2016-01-01  ..  2016-04-08  2016-04-09
----------------------------------------------
1       ..              4430        345
2       ..              11043       0
3       ..              0           12066
5       ..              13045       0
9       ..              0           15344
</code></pre>

<p>I understand I need dynamic SQL here to loop with a different date every time and <code>stuff()</code> to create multiple columns from rows in the resultset coming from <code>#usertime</code>. But I do not understand on how to use these funcionalities. Could anyone help me along?</p>