用于在重复键上插入更新的SQL查询是错误的

时间:2016-04-17 14:34:43

标签: sql sql-server

我在以下查询中收到错误

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'

附近的语法不正确

如何解决?

1 个答案:

答案 0 :(得分:2)

首先,你的select语句错误。

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中没有ON DUPLICATE KEY指令。快速搜索在中找到了许多参考文献,但 不是

要在Sql server中实现这种行为,您应该使用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)