title: Declare dynamic table which will use later in sql server procedures?
body: <p>I am working on sql stored procedure and I got some issue description given below: </p>
  
  <p><strong>Working Process</strong></p>
  
  <p>Declare a table name <code>@summaryTable</code></p>
  
  <p><code>DECLARE @summaryTable table (
  id int identity(1,1),
  )
  </code>
  Then make a query and then insert data into table <code>@summaryTable</code>, code given below:</p>
  
  <p><code>set @query = "Select * from Foo"
  insert into @summaryTable exec(@query)</code></p>
  
  <p><strong>Problem</strong></p>
  
  <p>When I print table name such as <code>print @summaryTable</code>, simply it give me the
   error that</p>
  
  <pre><code>`Msg 137, Level 16, State 1, Procedure summaryReportExport, Line 71
  Must declare the scalar variable "@summaryTable".`
  </code></pre>
  
  <p>Actually I need to use above table-name while creating <em>.csv</em> file such as </p>
  
  <pre><code>Declare @resultSet nvarchar(max)
  set @resultSet = "Select foo from '+@summaryTable"
  Declare @sql varchar(8000) set @sql = 'xp_cmdshell  '
  Declare @fileName varchar(8000) set @fileName = 'c:/test.csv'
  set @sql = @sql +   '''' + ' bcp "' + @resultSet+'"'  +' queryout '+ @fileName  +' -T -c -t,' + '''' ;
  print @sql
  EXEC    (@sql)
  </code></pre>
  
  <p>Any help would be appreciated?</p>