SQL Server 2005 and temporary table scope

Local temporary tables (start with #) are limited to your session; other sessions, even from the same user/connection string, can’t see them. The rules for the lifetime depend on whether the local temporary table was created in a stored procedure:

  • A local temporary table that is created in a stored procedure is dropped when the procedure ends; other stored procedures, or the calling process, can’t see them.
  • Other local temporary tables are dropped when the session ends.

Global temporary tables (start with ##) are shared between sessions. They are dropped when:

  • The session that created them ends
  • AND no other session is referring to them

This command can be handy to see which temporary tables exist:

select TABLE_NAME from tempdb.information_schema.tables 

And this is handy to drop temporary tables if you’re not sure they exist:

if object_id('tempdb..#SoTest') is not null drop table #SoTest

See this MSDN article for more information.

Leave a Comment