Search code examples
sqlsql-servertemp-tables

Session-global temporary tables in SQL Server


In SQL Server, temporary tables with a name like #temp has a local scope. If you create them in your session, everything in your session can see them, but not outside your session. If you create such a table within a stored procedure, the scope is local to that procedure. So when the proc exits, the table vanishes.

The only alternative I am aware of, is to use tables with a name like ##temp. These are temporary, but are visible server-wide. So if I create the table in my session, Bob in the office next door will also see them.

What I am looking for is somewhere in the middle, so I can create the table within a stored procedure and have that table be available to my session even after the stored proc exits. The nearest I have been able to find, is to create the table with only one field on it and then alter it within the stored proc. That seems like a bit of a kludge, though.


Solution

  • Could you not create the table when you start the session, then execute the stored proc, then do whatever else you want to do to the table after the stored proc executes?