Thursday, November 5, 2009

SQL dyanmic queries run in separate connections

In SQL Server 2005, it appears that all dynamic queries run in separate connections from that of the query which generated them. This makes a big difference if you are using connection-specific temp tables (e.g., #MyTempTable).

Here's a few examples in SQL Management Studio to demonstrate what's going on.

Query:

--in a dynamic query, create a local temp table and select from it
PRINT 'Example A:'
EXEC('CREATE TABLE #ConnectionTempTable ( [Foo] INT, [Bar] BIT, [Junk] NVARCHAR(100) ) SELECT * FROM #ConnectionTempTable')
PRINT '------'

--in a dynamic query, create a global temp table; then in the static query, drop it
PRINT 'Example B:'
EXEC('CREATE TABLE ##GlobalTempTable ( [Foo] INT, [Bar] BIT, [Junk] NVARCHAR(100) )')
DROP TABLE ##GlobalTempTable
PRINT '------'

--in a dynamic query, drop the local temp table from Example A (FAILS!)
PRINT 'Example C:'
EXEC('DROP TABLE #ConnectionTempTable')
PRINT '------'

--in a dynamic query, recreate the temp table from Example A (FAILS!)
PRINT 'Example D:'
EXEC('CREATE TABLE #ConnectionTempTable ( [Foo] INT, [Bar] BIT, [Junk] NVARCHAR(100) )')
SELECT * FROM #ConnectionTempTable


Results:

Example A:

(0 row(s) affected)
------
Example B:
------
Example C:
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '#ConnectionTempTable', because it does not exist or you do not have permission.
------
Example D:
Msg 208, Level 16, State 0, Line 20
Invalid object name '#ConnectionTempTable'.

No comments: