title: Incorrect syntax error on exec of a stored procedure
body: <p>I have a sproc that goes as follow:</p>
  
  <pre><code>    ALTER PROCEDURE [dbo].[GetProjectPaymentSchedules]
      @StartDate datetime
      AS
      BEGIN
          IF @StartDate IS NULL 
          BEGIN
              SET @StartDate = DateAdd(YY, -100, GetDate())
          END
          -- create our variables
          DECLARE 
          @query VARCHAR(max),
          @years VARCHAR(2000)
  
          SELECT  @years = STUFF((SELECT ISNULL(
                                           (SELECT * 
                                            FROM  
                                            (SELECT DISTINCT '],[' +  ltrim(Cast(PaymentDueDate as varchar(50))) As TheDate
                                             FROM    PaymentSchedule
                                             WHERE PaymentDueDate &gt; @StartDate
                                             Union all
                                             Select DISTINCT '],[' + ltrim(Cast(DateIncurred as varchar(50))) As TheDate
                                             FROM Expense
                                             WHERE  DateIncurred &gt; @StartDate
                                             ) Sub 
                                           ORDER BY ('],[' + ltrim(Cast(TheDate as varchar(50))))
                                           FOR XML PATH('')), 0)),1, 2, '') + ']'
      SET @query =
  
      'SELECT * 
      FROM
  
  (
      (select p.Project_Desc, s.Scope_ID, ps.PaymentDueDate, ps.PaymentAmount
      from Project p
      join dbo.Scope s
      ON  s.Project_ID = p.Project_Id
      join dbo.PaymentSchedule ps
      ON ps.Scope_ID = s.Scope_ID)
      UNION ALL
      (select  ec.CategoryDesc AS Category, s.Scope_ID AS Scope, e.DateIncurred, e.ExpAmount
      from Expense e
      join dbo.ExpenseCategory ec
      on e.ExpCategory = ec.CategoryId
      join Scope s
      on (e.ScopeId = s.Scope_ID or e.ScopeId IS Null) )
  
  )t
  
  PIVOT (SUM(PaymentAmount) FOR PaymentDueDate
  
  IN ('+@years+')) AS pvt
  order by pvt.Scope_ID'
  
  
  
  EXECUTE (@query)
      END
  </code></pre>
  
  <p>The creation/alteration poses no problems, but when I try to execute it as follows:</p>
  
  <pre><code>    exec dbo.AMEP_GetProjectPaymentSchedules '07-16-2012'
      exec dbo.AMEP_GetProjectPaymentSchedules NULL
  </code></pre>
  
  <p>Both result in the following:</p>
  
  <blockquote>
    <p>Msg 102, Level 15, State 1, Line 24<br>
    Incorrect syntax near '>'.<br>
    Msg 102, Level 15, State 1, Line 24<br>
    Incorrect syntax near '>'.</p>
  </blockquote>
  
  <p>I can't seem to figure what is throwing the error</p>
  
  <p>Any help is appreciated</p>