Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi
I want to insert records from one table to another one it give me error
Violation of PRIMARY KEY constraint 'Table1$PK_KndNr'. Cannot insert duplicate key in object 'dbo.Table1'.


SQL
insert into Table1(KndNr,Anrede, Name, Vorname, AdrZusatz, Strasse, Ort, [Tel_Privat], [Tel_Geschäft], 
Fax, Natel, Email, Geburtsdatum,ZahlungsKondition)

select distinct Kundennummer,Anrede,Name,Vorname,Zusatz,Strasse,Ort,[Telefon 1],[Telefon 2],
Fax,Natel,[E-Mail],Geburtstag,1

from table2
WHERE not exists (select * from Table1
                  where Table1.KndNr = table2.Kundennummer);


what will be correct query to avoid duplicate records in source table.
Posted

Refer this article[^]
 
Share this answer
 
use this...
SQL
insert into Table1

select distinct Kundennummer,Anrede,Name,Vorname,Zusatz,Strasse,Ort,[Telefon 1],[Telefon 2],
Fax,Natel,[E-Mail],Geburtstag,1
from table2
WHERE not exists (select * from Table1
                  where Table1.KndNr = table2.Kundennummer)


Note: when select records mention columns in order in which the destination table have
Happy Coding!
:)
 
Share this answer
 
Comments
Rupali Jadhav 9-Jan-13 2:37am    
Thanks. But I am not inserting values in all the columns of table1
Aarti Meswania 9-Jan-13 2:39am    
then remove that column names from select statement

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900