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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 insert help
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

oracle765
Starting Member

Australia
13 Posts

Posted - 03/06/2013 :  19:17:52  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3873 Posts

Posted - 03/06/2013 :  19:50:19  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000