title: exec sp_executesql @sql and exec (@sql)  SQL Server
body: <p>A Dynamic SQL query from <a href="https://stackoverflow.com/questions/5239890/dynamic-sql-pivot-by-column-sql-server">lobodava</a> is:</p>
  <pre><code>declare @sql nvarchar(4000) =
      N';with cteColumnts (ORDINAL_POSITION, COLUMN_NAME) as 
      (
          select ORDINAL_POSITION, COLUMN_NAME 
          from INFORMATION_SCHEMA.COLUMNS 
          where TABLE_NAME = N'''+ @tableName + ''' and COLUMN_NAME like ''' + @columnLikeFilter + '''
      ),
      cteValues (ColumnName, SumValue) as
      (
          SELECT ColumnName, SumValue
          FROM 
             (SELECT ' + @sumColumns + '
             FROM dbo.' + @tableName + ') p
          UNPIVOT
             (SumValue FOR ColumnName IN 
                (' + @columns + ')
          )AS unpvt 
      )
      select row_number() over(order by ORDINAL_POSITION) as ID, ColumnName, SumValue
      from cteColumnts c inner join cteValues v on COLUMN_NAME = ColumnName
      order by ORDINAL_POSITION'
  </code></pre>
  <p><strong>exec sp_executesql @sql<br />
  --OR<br />
  exec (@sql)</strong></p>
  <p>Why did lobodava pick <code>exec sp_executesql @sql</code> and not <code>exec(@sql)</code>
  So what is the difference here?<br />
  Is it better to use <code>sp_executesql on recursive dynamic queries</code>?<br />
  In other post they say <code>sp_executesql</code> is more likely to promote query plan reuse...
  So it helps in these kind of queries?</p>