I’m using SQL Server 2008 R2. I have a source table of data (I_Vendor) that may have duplicates on the CompanyName column. I want to import that data into a new table (Vendor) but the new table has a Name column (that corresponds to CompanyName) with a unique constraint on it. It’s been a while since I’ve done SQL but I saw the MERGE function, and it appears it fits the bill. I wrote the following:
MERGE Vendor AS T
USING I_Vendor AS S
ON (T.Name = S.CompanyName)
WHEN NOT MATCHED BY TARGET
THEN INSERT(VendorId, Name, ContactName, ContactInfoId)
VALUES(S.Vendor_ID, S.CompanyName, S.ContactName, S.Vendor_ID+10000);
It generates a “Violation of UNIQUE KEY constraint” and gives the name of the unique constraint on Vendor.Name. Anybody know what I’m doing wrong?
Your
MERGEstatement will insert all rows fromI_Vendorthat do not have a matching row in theVendortable.For example, suppose there are two rows in the
I_Vendortable with company name “X”, and further suppose that company name “X” does not appear in theVendortable, then both rows will be inserted into theVendortable, violating the constraint.To fix the problem, you need to ensure that there is only one row per company name in the source data of the
MERGEstatement. The following merge statement does this, but as Aditya Naidu has already pointed out, we don’t know what you want to do when there multiple records with the same company name in theI_Vendortable: