-2

I used the following code to update or Insert record from one table to another but the insert statement doesn't skip when duplicate record. How can i bypass that?

I get the following error. I want to skip duplicate record and insert the new

Msg 2627, Level 14, State 1, Line 6 Violation of PRIMARY KEY constraint 'PK_MIBOMD_KEY_0'. Cannot insert duplicate key in object 'dbo.MIBOMD'. The duplicate key value is ( , 0, 1). The statement has been terminated.

MERGE [MIBOMD] AS TARGET
USING [whl] AS SOURCE 


ON (TARGET.[bomItem] = SOURCE.ItemID AND TARGET.bomEntry = SOURCE.bomEntry AND TARGET.bomRev = SOURCE.rev)

WHEN MATCHED AND TARGET.bomEntry = SOURCE.bomEntry 
AND TARGET.partId <> SOURCE.partid THEN 
UPDATE SET TARGET.partId = SOURCE.partid

WHEN NOT MATCHED BY TARGET THEN 
INSERT (partId,bomEntry, srcLoc, qty, lead) 
VALUES (SOURCE.partid, SOURCE.bomEntry, 'R14SDS', SOURCE.qty, SOURCE.lead);

1 Answers1

1

As you stated, the uniqueness in the source is guaranteed by ItemID + PartID. Meanwhile, you are matching by source (ItemID,bomEntry,rev)=target.(bomItem,bomEntry,bomRev).

It is entirely possible that you will have something with the same set of (ItemID,bomEntry,rev) in the source but have two different PartID.

Also, among the INSERTed columns you specified, there is no bomRev,bomItem.
Are there default constraints on those columns? Will they guarantee uniqueness?

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
DVT
  • 3,014
  • 1
  • 13
  • 19