title: SQL Server: assigning dynamic SQL query to variable and executing
body: <p>I have a scenario where I have to execute a dynamic SQL query based on table name. </p>
  
  <p>For example i have a table X</p>
  
  <pre><code>|**table name**|  **Query**                                               |
  |--------------|------------------------------------------------------------|
  | A            |select ' +@somevariable1+ ' from '+@servername+ @table_name |
  </code></pre>
  
  <p>So my query looks like</p>
  
  <pre><code>Set @sql = (select query from X where table name =@table_name)   
  Exec @sql
  </code></pre>
  
  <p>Here the <code>exec @sql</code> is not working. Any ideas on how to exec this dynamic SQL query?</p>