SQL Server SELECT INTO and Blocking With Temp Tables

Mitchel Sellers picture Mitchel Sellers · Aug 19, 2009 · Viewed 56k times · Source

So, recently a DBA is trying to tell us that we cannot use the syntax of

SELECT X, Y, Z
INTO #MyTable
FROM YourTable

To create temporary tables in our environment, because that syntax causes a lock on TempDB for the duration of the stored procedure executing. Now, I've found a number of things that detail how temporary tables work, scope of execution, cleanup and the like. But for the life of me, I don't see anything about blocking because of their use.

We are trying to find proof that we shouldn't have to go through and do CREATE TABLE #MyTable... for all of our temporary tables, but neither side can find proof. I'm looking for any insight SO people have.

Additional Information

Currently working with SQL Server 2005, and soon to be SQL Server 2008 (Enterprise editions)

Answer

BradC picture BradC · Aug 19, 2009

That advice has been floating around for a long time:

Bottlenecks in SQL Server 6.5

Many people use a SELECT...INTO query to create a temporary table, something like this:

SELECT * INTO #TempTable FROM SourceTable

While this works, it creates locks against the tempdb database for the duration of the SELECT statement (quite a while if you are trawling through a lot of data in the source table, and longer still if the SELECT...INTO is at the start of a longer-running explicit transaction) While the lock is in place, no other user can create temporary tables. The actual location of the bottleneck is a lock on tempdb system tables. In later versions of SQL Server, the locking model has changed and the problem is avoided.

Fortunately, it was only a problem for SQL 6.5. It was fixed in 7.0 and later.