我在以下查询中出错
INSERT INTO tableName3 (column1, column2) SELECT b.column1, SUM (a.column2) AS SumColumn2 FROM tableName1 AS a JOIN tableName2 AS b ON a.column1 = b.column2 GROUP BY b.column2 ON DUPLICATE KEY UPDATE tableName3 SET column2 = SUM (a.column2) AS SumColumn2
错误消息是
关键字“ ON *”附近的语法不正确
和
关键字“ AS”附近的语法不正确
如何解决?
首先, 您的选择语句是错误的。
SELECT b.column1, SUM (a.column2) AS SumColumn2 FROM tableName1 AS a JOIN tableName2 AS b ON a.column1 = b.column2 GROUP BY b.column2
可能应该将其分组b.column1,否则,您将得到一个异常,因为select子句中的列必须出现在group by子句中或sql- server中的聚合函数中
b.column1
其次 ,ON DUPLICATE KEYSql server中没有指令。一个快速搜索发现,在这个许多人提到的MySQL,但MySQL的是 不是 SQL服务器。
ON DUPLICATE KEY
要在Sql Server中实现这种行为,您可能应该使用MERGE语句。
MERGE
您的代码应如下所示:
MERGE tableName3 AS target USING ( SELECT b.column1, SUM (a.column2) AS SumColumn2 FROM tableName1 AS a JOIN tableName2 AS b ON a.column1 = b.column2 GROUP BY b.column1 ) AS source (column1, SumColumn2) ON (target.column1= source.column1) WHEN MATCHED THEN UPDATE SET column2= source.SumColumn2 WHEN NOT MATCHED THEN INSERT (column1, column2) VALUES (source.column1, source.SumColumn2)