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:
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
I have no control over the function and can only use its output. The totaltime
is in seconds.
From another table, I can select the dates in a year:
select * from dates;
date
----------
2016-01-01
...
2016-04-08
2016-04-09
I would like to run the custom function usertime
for each date
in the dates
table and store the result in a temp table, as follows:
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
This would require me to call usertime
in a loop, pseudo:
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
I understand I need dynamic SQL here to loop with a different date every time and stuff()
to create multiple columns from rows in the resultset coming from #usertime
. But I do not understand on how to use these funcionalities. Could anyone help me along?