Wrap your current code in a procedure with parameters, for example:
CREATE PROCEUDRE dbo.CalcTime @Period varchar(100)
and using appropriate data types.
Then create a second procedure. In this case, define another temporary table, for example
CREATE TABLE #Results ( Name varchar(100) not null -- Or however long it might get ,Period varchar(100) not null -- Ditto ,TotalTime int null -- * )
Scroll through each period for which you want to define data. For each period, call the CalcTime stored procedure and dump the results to the temp table. Two ways to do this, use
INSERT
or by defining a temporary table in the calling procedure, you can refer to it in the called procedure in the standard expression INSERT... SELECT...
Also in a loop, build a comma-separated line that lists all the period labels, for example
SET @AllPeriodLabels = isnull(@AllPeriodLabels + ',', '') + @ThisPeriodLabel
or,
SET @AllPeriodLabels = isnull(@AllPeriodLabels + ',', '') + '[' + @ThisPeriodLabel + ']' -- **
Use this to build a dynamic SQL expression in the temp table, and you are done. As mentioned in the comments, there are any SO posts on how to do this, and here are links to two: first, discusses the creation of a dynamic summary operator, and the second uses similar tactics to claim non-privilege.
* Avoid inline spaces in object names, they will only hurt you.
** Good, sometimes you need to do this.