Generating and accessing data of a fixed column layout is easy. You can create local temp tables up-front, and populate them by calling stored proc
One clunky but possible option is to create a single-column table in the caller, then alter it in the callee. This gets around the scope issue but makes things quite a bit harder...
If you build a stored procedure that accepts input and output table names, which makes the second table look exactly like the first by dropping and adding columns, you might have a more general solution.
Selecting from tempdb.INFORMATION_SCHEMA.COLUMNS
will let you find the column information about any temp table (which you can detect by whether the table name starts with #
). Here's an example:
CREATE TABLE #blah (a int)
SELECT *
FROM tempdb.INFORMATION_SCHEMA.COLUMNS
WHERE Object_id('tempdb.dbo.' + TABLE_NAME) = Object_id('tempdb.dbo.#blah')
DROP TABLE #blah
Note that the table name in the view is not #blah
(it will probably be something like #blah___{lots of underscores}___00000000021D
thus the use of Object_id()
to correlate the two.
To use it practically, instead of filling the first table with data, then morphing the second table and copying the data into it, I would suggest creating an empty table first by running your process with an added TOP 0
or WHERE 1 = 0
, then copying the table's structure to the correct one with your table-copying SP, then running the data process for real to insert only once to the correct table.
Like I said, clunky, but could be useful in some narrow situations where no other options are available.