MERGE
您可以(应该)重写它以使用子查询或 CTE 过滤重复行并选择正确的行,而不是直接使用 @MergeData 作为语句的源MERGE
WITH CTE_MergeData AS
(
SELECT *
, ROW_NUMBER() OVER (PARTITION BY ProductCompanyId, ProductId ORDER BY ProductId DESC) RN --find some better order
FROM @MergeData
)
MERGE INTO @SomeTable T
USING (SELECT * FROM CTE_MergeData WHERE RN = 1) S
ON T.ProductCompanyId = S.ProductCompanyId AND T.ProductId = S.ProductId
WHEN MATCHED THEN
UPDATE
SET T.Name = S.Name,
T.Price = S.Price
WHEN NOT MATCHED THEN
INSERT (ProductCompanyId, ProductId, Name, Price)
VALUES (S.ProductCompanyId, S.ProductId, S.Name, S.Price)
OUTPUT S.ProductCompanyId, S.ProductId, Inserted.Id INTO @MergeProductsResults;