Skip to content
Advertisement

Select * into #Temp not working in dynamic SQL

When I create a temporary table and insert data into that temporary table through dynamic SQL its work fine. But when I use select * into #TempTable1 from YourTable in dynamic SQL it throw error. I am unable to understand the cause of this error.

Table:

Working Code:-

Not Working Code:

Error:

Msg 208 Level 16 State 0 Line 4 Invalid object name ‘#TempTable1’.

For Reference data is here.

Advertisement

Answer

The cause of this error is that a temp table is session bound and your dynamic SQL runs in a separate session.

Use a global temp table (prefix: ##) and make this one unique by naming (i.e. add a guid to the name). This way the dynamic SQL can see it.

Different types temporary tables: http://www.sqlines.com/articles/sql-server/local_and_global_temporary_tables

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement