A temporary table with a hash (#) or double hash (##) is a temporary table stored in the system database tempdb. This table exists only for the duration of the user session ID that created it. There are two types of temporary tables:
Local Temporary Table
A local temporary table is accessible only within the context of the session that created it. This means that it can be seen only by the user executing the script.
Creating a Local Temporary Table
You can easily create a local temporary table within Session 1 with the following query:
SELECT 1 AS Number
INTO #Temp_table;
If you open a new session (Session 2) and execute a query on this temporary table, you will encounter an error “Invalid object name ‘#Temp_table'”. This error occurs because the temporary table was created in Session 1, and Session 2 cannot access it.
Global Temporary Table
A global temporary table, on the other hand, can be accessed by different sessions. This means that other users can work with it.
Creating a Global Temporary Table
In Session 1, let’s create the same table, but this time it will be global (##Temp_table):
Now, if you query the table from a different session, you will get results because this time, the table is visible to other sessions:
In summary, local temporary tables are accessible only within the session that created them and are automatically dropped when that session ends. Global temporary tables can be accessed by different sessions, persist until all referencing sessions are closed, and must be explicitly dropped when they are no longer needed. The choice between them depends on your specific use case and data sharing requirements within your SQL Server environment.