MERGE Query and deleting records

前端 未结 4 1582
花落未央
花落未央 2021-01-01 09:02

I have a table that looks something like:

AccountID, ItemID
1, 100
1, 200
2, 300

I have a proc that accepts a table value parameter which u

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 09:57

    I can think of two obvious ways but both of them involve processing the TVP again.

    The first is simply to change the DELETE condition

        WHEN NOT MATCHED BY SOURCE 
        AND target.AccountId IN(SELECT AccountId FROM @Items) THEN
            DELETE;
    

    The second is to use a CTE to restrict the target

    WITH cte as
    (
    SELECT ItemId, AccountId 
    FROM @myTable m
    WHERE EXISTS 
      (SELECT * FROM @Items i WHERE i.AccountId = m.AccountId)
    )
          MERGE INTO cte as target
            USING @Items Items
               ON (Items.AccountId = target.AccountId) AND
                  (Items.ItemId = target.ItemId)
            WHEN NOT MATCHED BY TARGET THEN
                INSERT (AccountId, ItemId)
                VALUES (Items.AccountId, Items.ItemId)
             WHEN NOT MATCHED BY SOURCE THEN 
                DELETE;
    

提交回复
热议问题