title: Error executing dynamic sql query in phpmyadmin(error : #1046)
body: <p>I trying to run my dynamic query in PhpMyAdmin but mysql display this:</p>
  
  <blockquote>
    <p>ERROR: #1064 - You have an error in your SQL syntax; check the
    manual that corresponds to your MySQL server version for the right
    syntax to use near 'DECLARE @DynamicQuery AS nvarchar(max) DECLARE
    @AgrColumns AS nvarchar(max)' at line 1</p>
  </blockquote>
  
  <p>This is my query :</p>
  
  <pre><code>DECLARE @DynamicQuery AS nvarchar(max)
  DECLARE @AgrColumns AS nvarchar(max)
  
  --Get distinct values of the Column 
  SELECT @AgrColumns = ISNULL(@AgrColumns + ',', '') + 'SUM(CASE WHEN REASON_NAME = ''' + REASON_NAME + ''' THEN cnt ELSE 0 END) AS ' + QUOTENAME(REASON_NAME)
  FROM (SELECT DISTINCT REASON_NAME FROM Reason) AS Reasons
  
  --Prepare the query using the dynamic 
  SET @DynamicQuery =
  N'SELECT ' + @AgrColumns + ' FROM 
  (
      SELECT r.REASON_NAME, SUM(CASE WHEN c.ID is null OR rg.ID IS NULL THEN 0 ELSE 1 END) AS cnt 
      FROM Reason r
      LEFT JOIN Chat c ON (c.REASON_ID = r.ID)
      LEFT JOIN Reason_Group rg ON (r.REASON_GROUP_ID = rg.ID)
      GROUP BY REASON_NAME
  ) inn'
  
  --Execute the Dynamic Query
  EXEC sp_executesql @DynamicQuery
  </code></pre>
  
  <p>First table Chat:</p>
  
  <pre><code>ID    REASON_ID    DEPARTMENT_ID    
   1      46           1
   2      46           1
   3      50           1
   4      50           2
   5      100          1 
   6      100          2
  </code></pre>
  
  <p>Second table Reason:</p>
  
  <pre><code>ID    REASON_NAME     REASON_GROUP_ID
  46    Reason1         1
  50    Reason2         1
  100   Reason3         2
  101   Reason4         2
  105   Reqson5         3
  </code></pre>
  
  <p>Third table Reason_Group :</p>
  
  <pre><code>ID    NAME
  1     Group1
  2     Group2
  3     Group3
  </code></pre>
  
  <p>How can i solve the problem ?
  PhpMyAdmin Version: 4.2.11</p>