Question

In a stored procedure I dynamically create a temp table by selecting the name of applications from a regular table. Then I add a date column and add the last 12 months. The result looks like this:

Two dynamic columns and one date column.

So far so good. Now I want to update the data in columns by querying another regular table. Normally it would be something like:

UPDATE ##TempTable
SET [columName] = (SELECT SUM(columName)
FROM RegularTable
WHERE FORMAT(RegularTable.Date,'MM/yyyy') = FORMAT(##TempMonths.x,'MM/yyyy'))

However, since I don't know what the name of the columns are at any given time, I need to do this dynamically.

So my question is, how can I get the column names of a temp table dynamically while doing an update?

Thanks!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top