如何迭代填充临时表并将结果填充()到列中?

Pr0*_*0no 6 sql sql-server

如果我想知道每个用户在某一天在内联网上花了多少时间,我可以使用自定义功能 - 2个示例:

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
Run Code Online (Sandbox Code Playgroud)

我无法控制该功能,只能使用其输出.在totaltime以秒为单位.

从另一张表中,我可以选择一年中的日期:

select * from dates;

date
----------
2016-01-01
...
2016-04-08
2016-04-09
Run Code Online (Sandbox Code Playgroud)

我想运行自定义函数usertime为每个datedates表和结果存储在一个临时表,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

这需要我调用usertime一个循环,伪:

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
Run Code Online (Sandbox Code Playgroud)

我知道我需要动态SQL,每次循环使用不同的日期,并stuff()从结果集中的行创建多个列#usertime.但我不明白如何使用这些功能.任何人都可以帮助我吗?

Tom*_*m H 13

不需要任何循环(在SQL中几乎总是应该避免的).

SELECT
    T.userid,
    D._date,
    T.totaltime
FROM
    #dates D   -- Probably no need for a temporary table either...
CROSS APPLY dbo.usertime(D._date) T
Run Code Online (Sandbox Code Playgroud)

如果您需要转动这些结果,那么您也可以这样做.