我嘗試運行我在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
分號。你需要分號。 –
所有分號均爲真@Darwin von Corax –
代碼中沒有語句分隔符。你需要一個分號(或任何當前分隔符)來標記每個語句的結尾。 –