title: Msg 102, Level 15, State 1, Line 33 Incorrect syntax near ')'
body: <p>First time I am trying dynamic query as pivot table. I solve many error using SO. Now I am stuck in following <em>common error</em>. </p>
  
  <blockquote>
    <p>Msg 102, Level 15, State 1, Line 33
    Incorrect syntax near ')'.</p>
  </blockquote>
  
  <p>So I can't discover what mistake is..!</p>
  
  <p><strong>pivotEx</strong></p>
  
  <pre><code>create table pivotEx (name varchar(1), mark int, subject varchar(1))
  
  insert into pivotEx values
   ('a', 70,'t')
  ,('a', 80,'e')
  ,('b', 60,'t')
  ,('c', 80,'t')
  ,('c', 90,'e')
  ,('c', 40,'m')
  </code></pre>
  
  <p><strong>Static Query</strong>(working fine)</p>
  
  <pre><code> select name, [e],[m],[t] from(  
    select name, mark, subject from pivotEx 
   ) f
   pivot
   ( sum(mark) for subject in ([e],[m],[t])
   ) p
  </code></pre>
  
  <p><strong>Dynamic Query</strong>(what I am try)</p>
  
  <pre><code>declare @col varchar(max)
  declare @sql nvarchar(100)
  set @col = N''
  select @col +=  ',' + col from (select distinct quotename(subject) col from pivotex) colp
  select @col=SUBSTRING(@col,2,len(@col))
  select  @col
  set @sql = 
  N'select name, '+@col+' from(  
   select name, mark, subject from pivotEx 
  ) f
  pivot
  ( sum(mark) for subject in ('+@col+')
  ) p'
  
  EXEC sp_executesql @sql
  </code></pre>
  
  <p>Note:</p>
  
  <ol>
  <li>Using SQL Server 2014.</li>
  <li>Using SSMS 2012.</li>
  <li>I am new to Dynamic Query.</li>
  </ol>
  
  <p>Thanks,</p>
  
  <p>TamilPugal</p>