title: How to get row count from EXEC() in a TSQL SPROC?
body: <p>I have a TSQL sproc that builds a query as and executes it as follows:</p>
  
  <pre><code>EXEC (@sqlTop + @sqlBody + @sqlBottom)
  </code></pre>
  
  <p>@sqlTop contains something like SELECT TOP(x) col1, col2, col3... </p>
  
  <p>TOP(x) will limit the rows returned, so later I want to know what the actual number of rows in the table is that match the query.</p>
  
  <p>I then replace @sqlTop with something like:</p>
  
  <pre><code>EXEC ('SELECT @ActualNumberOfResults = COUNT(*) ' + @sqlBody)
  </code></pre>
  
  <p>I can see why this is not working, and why a value not declared error occurs, but I think it adequately describes what I'm trying to accomplish.</p>
  
  <p>Any ideas?</p>