I\'m using SQL Server 2000, and many of the stored procedures it use temp tables extensively. The database has a lot of traffic, and I\'m concerned about the thread-safety of cr
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;