title: Insert into temp table from exec call stored procedure
body: <p>I have a stored procedure where I insert a table into a temporary table and then I read that temp table row by row using a cursor:</p>
  
  <pre><code>USE [TEST_DB]
  GO    
  SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  
  ALTER PROCEDURE [dbo].[returnValidationFailures] 
  
  AS
  BEGIN
  
      SET NOCOUNT ON;
  
      SELECT TOP 0 * INTO  TempTbl FROM   USER
  
      DECLARE cursor1 CURSOR FAST_FORWARD FOR
          SELECT *
          FROM   USER
  
      OPEN cursor1
  
      INSERT INTO TempTbl 
      EXEC ('fetch next from cursor1')
  
      WHILE @@FETCH_STATUS = 0
          INSERT INTO TempTbl 
          EXEC ('fetch next from cursor1')
  
      CLOSE cursor1
  
      DEALLOCATE cursor1
  
      SELECT *
      FROM   TempTbl 
  
      DROP TABLE TempTbl 
  
  END
  </code></pre>
  
  <p>What I want here is to send the table name through a paramater like:</p>
  
  <pre><code>@TableNameParam varchar(10)
  </code></pre>
  
  <p>And then insert into temp table like:</p>
  
  <pre><code>SELECT TOP 0 * INTO  TempTbl FROM  @TableNameParam
  DECLARE cursor1 CURSOR FAST_FORWARD FOR
          SELECT *
          FROM   @TableNameParam
  </code></pre>
  
  <p>This doesn't work (obviously). But every other method I tried didn't work.
  Is there any way I can set the data of an EXEC call like:</p>
  
  <pre><code>EXEC ('SELECT * FROM ' + @TableNameParam
      ' WHERE STATUS=1')
  </code></pre>
  
  <p>into the temp table?</p>
  
  <p>Note: <strong>I DO NOT know the table structure.</strong></p>