title: How can I insert dynamic sql into temp table?
body: <p>I have this dynamic query, how can I insert the result of it into temp Table?
  The result of this query displays <code>(1000 row(s) affected)</code>
  But is any chance to dump those 1000 rows in a temp table?</p>
  
  <p>Something like that:</p>
  
  <pre><code>INSERT INTO #TempTable
  EXEC(@query)
  </code></pre>
  
  <p>Here is my query                                                     </p>
  
  <pre><code>DECLARE @cols AS NVARCHAR(MAX),
          @query  AS NVARCHAR(MAX)
  
  SET @cols =     STUFF((SELECT  ',' + QUOTENAME(c.locationCode) 
       FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename ='wind' order by c.CompanyName, c.LocationCode
       FOR XML PATH('')),1,1,'')
  
  set @query = 
                  'select *  into ##Temp
                  from 
  
                  (SELECT  QUOTEGUID as qguid, ' + @cols + ' from   
                          (
                              select 
                                      QuoteGUID, 
                                      LocationCode, 
                                      LineName,
                                      LineGUID
                              from Catalytic_vw_PolicyLocationCode 
                         )  x
                          pivot 
                          (
                               max(locationCode)
                              for locationCode in (' + @cols + ')
                          )p)x'
  
  EXEC sp_executesql @query;
  </code></pre>