Alexandre Brisebois
Alexandre Brisebois

Reputation: 6743

Using a temp table between stored procedures in SQL Server 2008

I currently have a main stored procedure calling many stored procedures:

Main --| 
     --|
       --| > Exec Pre-processing SP (create and populate #temp table)
     --|
       --| > Exec Actual update
     --|
       --| > Exec Post-Process (consume and drop #temp table)

The problem I'm currently having is that I need to grab the original values from the database, and the values being passed into the main stored procedure so that I can execute post processing to the update in the last step (stored procedure) being called.

I cannot change the stored procedure signatures or the main stored procedure.

When I try to execute this scenario, I get an invalid object in the post-processing stored procedure.

How can I pass my values from the first stored procedure to the last stored procedure.

Upvotes: 3

Views: 18405

Answers (2)

Ed Harper
Ed Harper

Reputation: 21495

If the main procedure is always run on a single thread and will never be called in parallel from multiple connections, you could declare your temporary table as a global temp table (##temp as opposed to #temp), assuming you are able to change the inner procedure.

This won't work if main is called from several connections at the same time.

Upvotes: 2

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

You need to create the temp table higher up in the calling hierarchy than all the stored procs that consume it. Since you say you cannot alter Main, the only chance to do this would be to create a new outermost procedure that creates #temp and then calls Main.

You can then modify the pre- procedure to populate the already existing table. You shouldn't need to explicitly drop the table anywhere.


Alternatively, you could create a permanent table, and include a spid column that indicates which connection data was inserted from. You'd also ensure that any selects/deletes against this table again use the @@SPID value. I posted this as an answer to Session-global temporary tables

Upvotes: 10

Related Questions