T-SQL Dynamic SQL and Temp Tables

You first need to create your table first then it will be available in the dynamic SQL.

This works:

CREATE TABLE #temp3 (id INT)
EXEC ('insert #temp3 values(1)')

SELECT *
FROM #temp3

This will not work:

EXEC (
        'create table #temp2 (id int)
         insert #temp2 values(1)'
        )

SELECT *
FROM #temp2

In other words:

  1. Create temp table
  2. Execute proc
  3. Select from temp table

Here is complete example:

CREATE PROC prTest2 @var VARCHAR(100)
AS
EXEC (@var)
GO

CREATE TABLE #temp (id INT)

EXEC prTest2 'insert #temp values(1)'

SELECT *
FROM #temp

Leave a Comment