How to access dataset in current scope generated by a call to a stored procedure in TSQL?

百般思念 提交于 2019-12-03 12:45:29

Create the temp table before the sp_executesql: it will still be in scope for "inner" scopes like the sp_executesql

Change the SQL to do an INSERT rather than SELECT..INTO...

Edit:

Make the table wide enough to cover all options.

Frankly, SQL is designed to work with fixed table definitions: variable output signatures (tables) leads to the problem you have...

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.

zhongxiao37

So, I am copying my answer from Insert results of a stored procedure into a temporary table. Hope it helps. Yes, it's global temporary table again and the only different is the GUID appended there.


I met the same problem and here is what I did for this from Paul's suggestion. The main part is here is to use NEWID() to avoid multiple users run the store procedures/scripts at the same time, the pain for global temporary table.

DECLARE @sql varchar(max) = '', 
@tmp_global_table varchar(255) = '##global_tmp_' + CONVERT(varchar(36), NEWID())
SET @sql = @sql + 'select * into [' + @tmp_global_table + '] from YOURTABLE'
EXEC(@sql)

EXEC('SELECT * FROM [' + @tmp_global_table + ']')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!