通过改进 ON/GROUP By Clause 更新和插入

Updates and inserts by improving ON/GROUP By Clause

这是源和目标的示例 table。我只有一个名为“Premise_ID”的唯一 ID。我想根据 Premise ID 更新目标 table。当我在 运行 下面提到 SQL 查询时,我收到下面提到的错误。我有多行具有相同的 Premise_ID 但具有不同的列 attributes.if 第一个 Premise_ID 匹配然后更新所有列属性。如果第二个 Premise_ID 与前一个相同,则只需添加包含所有列属性的另一行。有什么办法可以克服这个错误吗?

来源Table

目标Table

SQL 查询:

USE GIS_NewJersey
GO
WITH Source AS (
    SELECT Premise_ID, Division, InstallationType
    FROM sde.SAP_Load_test
),
Target AS (
    SELECT Premise_ID, Division, InstallationType
    FROM sde.PREMISE_test
)
MERGE Target t
USING Source s
  ON t.Premise_ID = s.Premise_ID
WHEN MATCHED THEN
  UPDATE SET
    Division = s.Division,
    InstallationType = s.InstallationType
WHEN NOT MATCHED THEN
  INSERT (Premise_ID, Division, InstallationType)
    VALUES (s.Premise_ID, s.Division, s.InstallationType)
;

错误:

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 SEARCH CONDITIONS 中使用 3 列,并使用 WHEN NOT MATCHED BY TARGETINSERTWHEN NOT MATCHED BY SOURCEDELETE

USE GIS_NewJersey
GO
WITH Source AS (
    SELECT Premise_ID, Division, InstallationType
    FROM sde.SAP_Load_test
),
Target AS (
    SELECT Premise_ID, Division, InstallationType
    FROM sde.PREMISE_test
)
MERGE Target t
USING Source s
  ON t.Premise_ID = s.Premise_ID
  AND t.Division = s.Division
  AND t.InstallationType = s.InstallationType
WHEN NOT MATCHED BY TARGET THEN
  INSERT (Premise_ID, Division, InstallationType)
    VALUES (s.Premise_ID, s.Division, s.InstallationType)
WHEN NOT MATCHED BY SOURCE THEN
  DELETE
;