// SQL Server 错误参考

SQL Server 错误 8672:MERGE 触及同一行两次

在 MERGE 中,某个目标行匹配了多个源行,因此它会被更新或删除两次。请让源数据在连接键上保持唯一。

错误编号
8672
严重性
16
类别
语法与编译
错误信息
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

它的意思

MERGE 要求每个目标行在 WHEN MATCHED 操作。如果 ON 条件允许两个源行匹配同一个目标行,SQL Server 无法决定应用哪个更新,并导致 8672 错误。

常见原因

  • 源表或临时数据中的重复键。
  • 一个 ON 子句未覆盖完整键的情况,例如键是 customer 加 date,却只按 customer 连接。

如何修复它

  1. 查找源中的重复键。

    SELECT CustomerId, COUNT(*) FROM staging.Customers GROUP BY CustomerId HAVING COUNT(*) > 1;
  2. 合并前先在 CTE 里对源数据去重,保留你要的那一行。

    WITH src AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY UpdatedAt DESC) AS rn
        FROM staging.Customers
    )
    MERGE dbo.Customers AS t
    USING (SELECT * FROM src WHERE rn = 1) AS s ON t.CustomerId = s.CustomerId
    WHEN MATCHED THEN UPDATE SET t.Name = s.Name
    WHEN NOT MATCHED THEN INSERT (CustomerId, Name) VALUES (s.CustomerId, s.Name);
  3. 把 ON 条件匹配完整键。

相关错误

更多语法和编译错误

代码和消息文本来自 Microsoft 数据库引擎事件和错误参考。浏览完整的 SQL Server 错误列表 或者 搜索每个数据库错误.

// 错误更少,修复更快

在 SQLly 中使用 SQL Server

适用于 macOS、Windows 和 Linux 的原生 SQL 客户端,智能感知能理解你的数据库模式,高危语句有防护,错误信息清晰,支持 SQL Server 以及你使用的其他数据库。