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.

Local Temporary Table Example

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):

Global Temporary Table Example

Now, if you query the table from a different session, you will get results because this time, the table is visible to other sessions:

Querying Global Temporary Table from Another Session

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.

Rate this post

Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zedníček and I have been working as a freelancer for many companies for more than 10 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

🔥 If you found this article helpful, please share it or mention me on your website

Leave a Reply

Your email address will not be published. Required fields are marked *