title: Dynamic SQL taking much much longer than the hard-coded equivalent
body: <p>I have a dynamic piece of SQL. It takes about 4 minutes to run. If I instead take the output of the SQL and run that instead, it takes about 20 seconds. Why the discrepancy? I know it would take some amount of time to build up the SQL in the dynamic version, but I can't imagine it's THAT expensive. </p>
  
  <p>Anyone have any ideas? The two queries should be identical, so I was suspecting it was something weird with query plan caching, but don't really have much of an idea.</p>
  
  <p><strong>Edit:</strong>
  To clarify what I mean by taking the output.</p>
  
  <p>In the dynamic SQL the last line is </p>
  
  <pre><code>EXEC sp_executesql @myQuery,
      N'@var1 INT,
      @var2 INT,
      @var2 INT',
      @var1,
      @var2,
      @var3
  </code></pre>
  
  <p>I took the value of myQuery and put it in its own SQL file. That is running at 20 seconds while the dynamic one that uses execute takes 4 minutes.</p>
  
  <p><strong>Edit 2</strong>
  I removed the parameters. I got interesting results. The dynamic SQL statement saw a performance improvement. The hardcoded version saw a huge performance hit. The two are about equal now.</p>