Hi,
I have 2 tables, wce_contact and PC_WiredOrder.
I want to copy data from PC_WiredOrder into wce_contact, that is not difficult. The issue comes when the PC_WiredOrder table has duplicates in it, it then conflicts with the unique primary key in the wce_contact table. That is because i'm using the customerid from PC_WiredOrderand for the uniqueid in wce_contact. So the duplicate rows customerid '333' in the example below, can't insert into the uniqueid of wce_contact table it attempts the first instance then the second and conflicts.
Here is the error:
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__wce_cont__AA522ACA7F60ED59'. Cannot insert duplicate key in object 'dbo.wce_contact'.
The statement has been terminated.
Below is some script to create the tables, insert some sample data and the attempt to insert script. This replicates the issue.
If anyone can help me to get round this I would be grateful, I have tried loads of options and can't get it! Thanks for your help
Script causing the issue.
I have 2 tables, wce_contact and PC_WiredOrder.
I want to copy data from PC_WiredOrder into wce_contact, that is not difficult. The issue comes when the PC_WiredOrder table has duplicates in it, it then conflicts with the unique primary key in the wce_contact table. That is because i'm using the customerid from PC_WiredOrderand for the uniqueid in wce_contact. So the duplicate rows customerid '333' in the example below, can't insert into the uniqueid of wce_contact table it attempts the first instance then the second and conflicts.
Here is the error:
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__wce_cont__AA522ACA7F60ED59'. Cannot insert duplicate key in object 'dbo.wce_contact'.
The statement has been terminated.
Below is some script to create the tables, insert some sample data and the attempt to insert script. This replicates the issue.
If anyone can help me to get round this I would be grateful, I have tried loads of options and can't get it! Thanks for your help
Code:
CREATE DATABASE temp3
GO
USE temp3
CREATE TABLE wce_contact
(
uniqueid VARCHAR(50) NOT NULL PRIMARY KEY,
emailaddress VARCHAR(150) NOT NULL,
)
INSERT INTO wce_contact VALUES (1, '1@1.com'), (2, '2@2.com');
CREATE TABLE PC_WiredOrder
(
id VARCHAR(50) NOT NULL PRIMARY KEY,
customerid VARCHAR(150) NOT NULL,
billingemail VARCHAR(150) NULL,
)
INSERT INTO PC_WiredOrder VALUES ('a', 333, '3@3.com'), ('b', 333, '3@3.com'), ('c', 444, '4@4.com');
Script causing the issue.
Code:
INSERT INTO wce_contact
(UNIQUEID, EMAILADDRESS)
SELECT t1.customerid,
t1.billingemail
FROM PC_WiredOrder t1
WHERE NOT EXISTS(SELECT EMAILADDRESS
FROM wce_contact t2
WHERE t2.EMAILADDRESS = t1.BillingEmail)