2016-02-19 79 views
0

我尝试运行我在phpMyAdmin动态查询,但MySQL的显示此:错误在phpMyAdmin执行动态SQL查询(错误:#1046)

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

这是我的查询:

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 

第一表聊天:

ID REASON_ID DEPARTMENT_ID  
1  46   1 
2  46   1 
3  50   1 
4  50   2 
5  100   1 
6  100   2 

二表原因:

ID REASON_NAME  REASON_GROUP_ID 
46 Reason1   1 
50 Reason2   1 
100 Reason3   2 
101 Reason4   2 
105 Reqson5   3 

三表Reason_Group:

ID NAME 
1  Group1 
2  Group2 
3  Group3 

我该如何解决这个问题呢? PhpMyAdmin版本:4.2.11

+1

分号。你需要分号。 –

+0

所有分号均为真@Darwin von Corax –

+1

代码中没有语句分隔符。你需要一个分号(或任何当前分隔符)来标记每个语句的结尾。 –

回答

1

声明只能出现在构成复合语句块的begin ... end block中。如果您不想使用存储的程序,请使用用户定义的变量set statement

但是,您尝试执行的代码似乎是ms sql而不是mysql,因此您需要认真重写整个代码,然后才能在mysql环境中运行它。

+0

我如何将它转换为mysql查询? @shadow –

+0

您研究了mysql语法并重写了代码。 – Shadow