Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 insert help

Author  Topic 

oracle765
Starting Member

13 Posts

Posted - 2013-03-06 : 19:17:52
I am trying to insert records into the database as follows
insert into lookuptable
select * from lookuptable1

which produces
Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'uqLookuptable1cols1'. Cannot insert duplicate key in object 'dbo.lookuptable'.
The statement has been terminated.

Is there a way to handle this error so I can carry on inserting the rest of the records into the table

A Lynch

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-06 : 19:50:19
See script below - replace the "uniqueColumn" with the column that is referenced in the constraint.
insert into lookuptable
select * from lookuptable1 a
WHERE NOT EXISTS (SELECT * FROM lookuptable b
WHERE b.uniqueColumn = a.uniqueColumn)
Go to Top of Page
   

- Advertisement -