Pregunta

I've got a stored procedure that accepts batches of product info. For each product, either insert it into the DB or Update it, if it already exists.

A product is defined by a composite key -> ProductCompanyId (where the product came from) and a ProductId (the unique Id, per company).

I'm trying to do a MERGE query. It works perfectly, until the batch has the same composite key in it more than once.

For example, lets imagine I have 10 products. 2 of these have the same comp-keys but different prices.

I thought the first 'row' would be inserted, with the 2nd row being an update.

Here is some FULL REPO sql code to show you what I've done.

It's far too hard to try and make sure there's only unique composite key's per batch. So, is there anything I can do?

I'm using SQL Server 2012 .. so I'm not sure if that's an issue.

¿Fue útil?

Solución

Instead of using @MergeData directly as source of your MERGE statement, you could (should) rewrite it to use subquery or CTE that will filter duplicate rows and choose the correct one to be used in 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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top