我尝试在PhpMyAdmin中运行我的动态查询,但mysql显示:
错误:#1064 - 您的SQL语法出错;检查 手册,对应右边的MySQL服务器版本 在'DECLARE @DynamicQuery AS nvarchar(max)DECLARE附近使用的语法 @AgrColumns AS nvarchar(max)'在第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
答案 0 :(得分:1)
声明只能出现在形成复合语句块的begin ... end block中。如果您不想使用存储的程序,请将用户定义的变量与set statement一起使用。
但是,您尝试执行的代码似乎是ms sql而不是mysql,因此您需要认真重写整个代码才能在mysql环境中运行它。