I think you can use something like the following.
select name as 'ColumnName'
from tempdb.sys.columns
where object_id = object_id('tempdb..##TempTable');
And then generate dynamic sql using something like the following.
DECLARE @tableName nvarchar(50)
SET @tableName = 'RegularTable'
DECLARE @sql NVARCHAR(MAX)
SET @sql = ''
SELECT @sql = @sql + ' UPDATE ##TempTable ' + CHAR(13) +
' SET [' + c.name + '] = (SELECT SUM([' + c.name + ']) ' + CHAR(13) +
' FROM RegularTable' + CHAR(13) +
' WHERE FORMAT(RegularTable.Date,''MM/yyyy'') = FORMAT(##TempMonths.x,''MM/yyyy''));' + CHAR(13)
from tempdb.sys.columns c
where object_id = object_id('tempdb..##MyTempTable');
print @sql
-- exec sp_executesql @sql;
Then print
statement in above snippet shows that the @sql
variable has the following text.
UPDATE ##TempTable
SET [Test Application One] = (SELECT SUM([Test Application One])
FROM RegularTable
WHERE FORMAT(RegularTable.Date,'MM/yyyy') = FORMAT(##TempMonths.x,'MM/yyyy'));
UPDATE ##TempTable
SET [Test Application Two] = (SELECT SUM([Test Application Two])
FROM RegularTable
WHERE FORMAT(RegularTable.Date,'MM/yyyy') = FORMAT(##TempMonths.x,'MM/yyyy'));
So now, you use sp_exec
to execute the updates as follows (un-comment it from above snippet).
exec sp_executesql @sql;
If it's a 1 time UPDATE
you can PRINT
the dynamic SQL statement (as shown above) and then execute it in the SSMS Query Windows.
I recommend you use the print
statement first to make sure the UPDATE
statements generated are what you want, and then do the sp_executesql
or run the printed UPDATE
statement in the query window.