I am writing a stored procedure for SQL Server 2008 in which I need to extract information from a set of tables. I do not know ahead of time the structure of those tables. There is another table in the same database that tells me the names and types of the fields in this table.
I am doing this:
declare @sql nvarchar(max)
set @sql = 'select ... into #new_temporary_table ...'
exec sp_executesql @sql
Then I iterate doing:
set @sql = 'insert into #another_temporary_table ... select ... from #new_temporary_table'
exec sp_executesql @sql
After that I drop the temporary table. This happens in a loop, so the table with be created, populated and dropped many times, each time with different columns.
This fails with the error:
Invalid object name: #new_temporary_table.
After some googling I have found that:
The table
#new_temporary_table
is being created in the scope of the call toexec sp_executesql
which is different from the one of my stored proc. This is the reason the nextexec sp_executesql
cannot find the table. This post explains it: http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/1dd6a408-4ac5-4193-9284-4fee8880d18aI could use global temporary tables, which are prepended with
##
. I can't do this because multiple stored procs could run at the same time and they would be affecting each other's stateIn this article it says that if I find myself in this situation I should change the structure of the database. This is not an option for me: http://www.sommarskog.se/dynamic_sql.html
One workaround I have found was combining all the select into #new_temporary_table..
and all the insert into ...
scripts into one gigantic statement. This works fine but it has some downsides.
If I do print @sql to troubleshoot, the text gets truncated, for example.
Do I have any other option? All ideas are welcome.