title: Inserting data into a temp table from an open query
body: <p>I've looked online and you can not drop variables into an open query so easily so I modified my query and it says the #TempOT temp table is "Invalid object name '#TempOT'."  What am I doing wrong that is causing the temp table not to get populated?</p>
  
  <pre><code>    BEGIN
  IF OBJECT_ID('tempdb..#TempOT') IS NOT NULL
  BEGIN
      DROP TABLE #TempOT
  END;
  
   DECLARE @TSQL As varchar(1024)
   DECLARE @AS400Query As varchar(1024)
   SET @AS400Query = 'SELECT * from blah.blahlibrary.AS400Table where DATETS  BETWEEN '+ @BegofMonthForAS400 + ' AND ' + @DateForAS400 
   SET @TSQL = 'SELECT * FROM OPENQUERY(ISERIES,' + '''' + @AS400Query +'''' + ')'
  
  INSERT INTO #TempOT
   EXEC(@TSQL)
  END
  </code></pre>
  
  <p>i have also tried this and it does not work</p>
  
  <pre><code>    BEGIN
  IF OBJECT_ID('tempdb..#TempOT') IS NOT NULL
  BEGIN
      DROP TABLE #TempOT
  END;
  
   DECLARE @TSQL As varchar(1024)
   DECLARE @AS400Query As varchar(1024)
   SET @AS400Query = 'SELECT * from valdosta.PRDATA.PRTIMELM where DATETS BETWEEN '+ @BegofMonthForAS400 + ' AND ' + @DateForAS400 
   SET @TSQL = ' INSERT INTO #TempOT SELECT * FROM OPENQUERY(ISERIES,' + '''' + @AS400Query +'''' + ')'
  
  
  EXEC(@TSQL)
  
  END
  </code></pre>