Are temporary tables thread-safe? Are temporary tables thread-safe? sql-server sql-server

Are temporary tables thread-safe?


For the first case, no, it is not possible, because #temp is a local temporary table, and therefore not visible to other connections (it's assumed that your users are using separate database connections). The temp table name is aliased to a random name that is generated and you reference that when you reference your local temp table.

In your case, since you are creating a local temp table in a stored procedure, that temp table will be dropped when the scope of the procedure is exited (see the "remarks section").

A local temporary table created in a stored procedure is dropped automatically when the stored procedure completes. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process which called the stored procedure that created the table.

For the second case, yes, you will get this error, because the table already exists, and the table lasts for as long as the connection does. If this is the case, then I recommend you check for the existence of the table before you try to create it.


Local-scope temp tables (with a single #) are created with an identifier at the end of them that makes them unique; multiple callers (even with the same login) should never overlap.

(Try it: create the same temp table from two connections and same login. Then query tempdb.dbo.sysobjects to see the actual tables created...)


Local temp tables are thread-safe, because they only exist within the current context. Please don't confuse context with current connection (from MSDN: "A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished"), the same connection can safely call two or more times a stored procedure that creates a local temp table (like #TMP).

You can test this behavior by executing the following stored procedure from two connections. This SP will wait 30 seconds so we can be sure the two threads will be running their over their own versions of the #TMP table at the same time:

CREATE PROCEDURE myProc(@n INT)AS BEGIN    RAISERROR('running with (%d)', 0, 1, @n);    CREATE TABLE #TMP(n INT);    INSERT #TMP VALUES(@n);    INSERT #TMP VALUES(@n * 10);    INSERT #TMP VALUES(@n * 100);    WAITFOR DELAY '00:00:30';    SELECT * FROM #TMP;END;