Published on

March 18, 2009

Understanding Local Temporary Tables in SQL Server

Recently, I received an interesting question from one of my blog readers regarding an error message related to local temporary tables in SQL Server. In this article, we will explore the reason behind this error and discuss the concept of local temporary tables.

The error message in question is: “Msg 2714, Level 16, State 6, Line 4 There is already an object named ‘#temp’ in the database.” This error occurs when attempting to create a local temporary table with a name that already exists in the database.

Local temporary tables are created using the hash (#) sign before the table name. They are only visible within the current connection and their scope ends when the connection is dropped. It is important to note that local temporary tables can have the same name in different connections simultaneously.

When SQL Server encounters a situation where multiple connections are using the same local temporary table name, it appends an incremental hex digit to the table name. This digit is reset when SQL Services are restarted. This is why when querying the sys.tables system table, we need to use the LIKE operator and ‘%temp%’ to compare the table names.

Let’s take a look at an example to better understand this behavior:

BEGIN
IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#temp%')
DROP TABLE #temp
CREATE TABLE #temp(id INT )
SELECT name
FROM sys.tables
WHERE name LIKE '%#temp%'
END
GO 10

In the above example, we create a local temporary table named #temp. We then query the sys.tables system table to observe how the hex numbers are suffixed to the local temporary table names. By running this code multiple times, you will notice that the hex digit changes each time.

To avoid the error mentioned earlier, we can use the following T-SQL code:

IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#temp%')
DROP TABLE #temp
CREATE TABLE #temp(id INT )

It is important to note that this code should only be used for temporary tables and not for physical tables. Also, make sure to replace #temp with the name of your temporary table.

In conclusion, local temporary tables in SQL Server have a unique behavior due to their scope being limited to the current connection. When multiple connections use the same table name, SQL Server appends an incremental hex digit to differentiate them. By understanding this concept, we can effectively create and manage local temporary tables in our T-SQL applications.

I hope this article has provided you with a clear understanding of local temporary tables in SQL Server. If you have any further questions or observations, please feel free to reach out to me. Your feedback is always valuable.

Thank you for reading!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.