I seem to be running into a problem with temp table garbage collection:
CREATE PROCEDURE dbo.SetTestTempTable(@value bit)
AS
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#TestTempTable') IS NOT NULL
DROP TABLE #TestTempTable
SELECT @value AS Value INTO #TestTempTable
GO
EXEC dbo.SetTestTempTable 1
SELECT * FROM #TestTempTable
The above code produces the error
Msg 208, Level 16, State 0, Line 3
Invalid object name '#TestTempTable'.
I think because #TestTempTable is getting garbage collected when the proc exits.
Is there a way of preventing this? I don’t want to have every caller need to explicitly create the temp table before calling the procedure.
UPDATE:
Why am I doing this?
I have the need to store some contextual information (basically a session variable). I was using CONTEXT_INFO for this. SQL Azure doesn’t support CONTEXT_INFO, so I’m refactoring accordingly. Essentially, I have a function:
GetMySessionVariableName()
and a procedure
SetMySessionVariableName(value)
Previously, this function and procedure used CONTEXT_INFO internally, and that worked fine. Now, with temp tables, it doesn’t…I’m open to suggestions on alternative approaches.
The #temp table is dropped (well, deferred dropped) when the stored procedure goes out of scope. So it is not available to you outside of the scope of the stored procedure. In order to see the contents of #temp after the procedure finishes, you need to create it before you execute the stored procedure, and populate it inside… or perform the select inside the stored procedure.
For the updated requirement, why not just use a permanent table with a key on UserID, and update your stored procedures to take UserID as a parameter? If you already have a Users table you could surely store updated session information in a column or two there. No CONTEXT_INFO or #temp table nonsense required.