title: TSQL: How to fill a variable using a generated sql command string without a cursor
body: <p>I'm trying to get the value of generated sql inside a stored procedure.<br>
  Executing this</p>
  
  <pre><code>   DECLARE @sSQL varchar(5000), @retval int
     DECLARE @tablename varchar(50)
  
     SELECT @tablename = 'products'
  
     SELECT @sSQL = 'SELECT @retval = MAX(ID)'
     SELECT @sSQL = @sSQL + ' FROM ' + @tablename
     EXEC (@sSQL) 
  
     SELECT @retval
  </code></pre>
  
  <p>I get </p>
  
  <pre><code>   Must declare the variable '@retval'.
  </code></pre>
  
  <p>How can I get the value without using a cursor (which I'm trying to avoid)?</p>