title: SQL Server. dynamic query error while using aggregate function
body: <p>I am little bit new to SQL. I am trying to run below shown dynamic query</p>
  <pre><code>SET @SQL ='
  select Distinct count(*) TotalCount,
      sum(case when ap.FormStatus = ''open'' then 1 else 0 end) AS Totalopenstatus,
      sum(case when ap.FormStatus = ''Pending'' then 1 else 0 end) AS TotalPendingstatus,
      sum(case when ap.FormStatus = ''Awaiting L1 Review'' then 1 else 0 end) AS TotalAssociates,
      sum(case when ap.FormStatus = ''Awaiting L2 Review'' then 1 else 0 end) AS TotalL1reviews,
      sum(case when ap.FormStatus = ''Awaiting Delivery Head'' then 1 else 0 end) AS TotalL2reviews
      from [dbo].[Appraisals] ap
      LEFT join [dbo].[FinalReviewClosures] fi ON ap.FinalReviewClosure_Id = fi.id
      join [dbo].[employees] emp ON fi.Employee_Id = emp.id
  where fi.FinancialYear ='+@FinancialYear +'  AND ap.Quarter = '+@Quarter+' '
  </code></pre>
  <p>but I get this error:</p>
  <blockquote>
  <p>Msg 245, Level 16, State 1, Procedure sp_GetReviewStatus, Line 51 [Batch Start Line 11]<br />
  Conversion failed when converting the nvarchar value</p>
  </blockquote>
  <p>Code:</p>
  <pre><code>select Distinct count(*) TotalCount,
      sum(case when ap.FormStatus = 'open' then 1 else 0 end) AS Totalopenstatus,
      sum(case when ap.FormStatus = 'Pending' then 1 else 0 end) AS TotalPendingstatus,
      sum(case when ap.FormStatus = 'Awaiting L1 Review' then 1 else 0 end) AS TotalAssociates,
      sum(case when ap.FormStatus = 'Awaiting L2 Review' then 1 else 0 end) AS TotalL1reviews,
      sum(case when ap.FormStatus = 'Awaiting Delivery Head' then 1 else 0 end) AS TotalL2reviews
      from [dbo].[Appraisals] ap
      LEFT join [dbo].[FinalReviewClosures] fi ON ap.FinalReviewClosure_Id = fi.id
      join [dbo].[employees] emp ON fi.Employee_Id = emp.id
  where fi.FinancialYear =2020-2021  AND ap.Quarter = Q3  AND emp.office = ' to data type int.
  </code></pre>
  <p>Please help me fix this problem.</p>