0

I'm performing an INSERT INTO SELECT statement in SQL Server. The situation is that there are two Primary keys of two different tables, without anything in common, that are both foreign keys of a third table, forming a composite primary key in that last table. This can usually be accomplished with a cross join - for example,

Table1.ID(PK)
Table2.Code(PK)

-- Composite PK for Table3
Table3.ID(FK)
Table3.Code(FK)

INSERT INTO Table3
SELECT ID, Code
FROM Table1
CROSS JOIN Table2
WHERE Some_conditions...

I'm getting a "Cannot insert duplicate key row" error. It will not allow Table2.Code to be repeated in Table3, since it is a unique ID, even though the primary key of Table3 is Table1.ID combined with Table2.Code. Hence, the following pairs should be recognized as different PK values in Table3 for example: {1024, PSV} and {1027, PSV}.

Is there a way to fix this, or have I designed this database incorrectly? I have considered creating a third unique ID for Table3, but it is highly impractical in this scenario.

Dean Zaslow
  • 87
  • 2
  • 9

3 Answers3

2

This will help you locate the problem:

SELECT ID, Code
FROM Table1
CROSS JOIN Table2
WHERE Some_conditions...
GROUP BY ID, Code
HAVING COUNT(*) > 1
shawnt00
  • 16,443
  • 3
  • 17
  • 22
1

I presume that the reason you are getting this error is because table 2 has multiple rows of the same code for the same ID.

For example, table 2 might have two or more rows of ID 1024 and code 'PSV'.

A simple solution to fix this would be to modify your code as follows:

INSERT INTO Table3
SELECT DISTINCT ID, Code
FROM Table1
CROSS JOIN Table2
WHERE Some_conditions...
Russ
  • 4,091
  • 21
  • 32
  • ^ I have tried this to no avail as well - There are NO duplicates of both records. IDs and Codes are both repeated, but never together. 1024 PSV, 1027 PSV, and 1024 RFT should represent 3 different PKs. – Dean Zaslow Aug 06 '15 at 20:54
0

SQL Server had created a unique, non-clustered index for Table3 that was preventing the INSERT INTO statement from executing. I disabled it with SQL Server Management Studio Object Explorer and it allowed me to enter the rows.

Dean Zaslow
  • 87
  • 2
  • 9