Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Key constraint issue

Status
Not open for further replies.

DomTrix

Programmer
Dec 28, 2004
94
GB
Hi, I have two tables both containing data under the same column headings and types, code and name. The name column is a unique index with an insert and update constraint.

I am trying to insert data from table2 to table1 when the data does not already exist in table1 but am getting a unique key constraint error (cannot insert duplicate key). My code is as follows:

Code:
INSERT INTO table 1
SELECT  table2.code,
        table2.description
FROM    table2
WHERE   NOT EXISTS (
           SELECT   table1.code 
           FROM     table1
           WHERE    table1.name = table2.name

Curiously, I can use the following, practically identical, code to copy the data one row at a time with no error:

Code:
INSERT INTO table 1
SELECT  TOP 1
        table2.code,
        table2.description
FROM	table2
WHERE 	NOT EXISTS (
           SELECT   table1.code 
           FROM     table1
           WHERE    table1.name = table2.name

Any ideas?

DT
 
ah yes, typo, should be:

Code:
INSERT INTO table 1
SELECT  table2.code,
        table2.name
FROM    table2
WHERE     NOT EXISTS (
           SELECT   table1.code 
           FROM     table1
           WHERE    table1.name = table2.name )
 
I should elaborate, sorry for double post, cant seem to be able to edit posts.

It was a typo in the post, that is not what is producing the error.

Thanks,

DT
 
No, it produces the same error. I tried it with some test data that I set up and it works fine. It is failing on a particular set of data (a clients monthly db update).

Oh, duh, just found out the reason while explaining the problem. Table2 does not use an index and contained duplicates! Table2 is created by a third party whos databases arent too clean!

Thnx for you help tho

DT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top